- Hands-On Server-Side Web Development with Swift
- Angus Yeung
- 206字
- 2021-06-10 19:00:23
Using the Logging API in a Vapor project
Vapor has its own pluggable logger framework. Since the Logging module is part of Vapor's Console package, it is included in all Vapor projects by default. You'll have access to all Logging APIs after you include import Vapor in a Swift file.
Vapor's Logging module includes the Logger protocol that declares common interfaces for all logger implementations. One example is SwiftyBeaver Logger for Vapor 3.0, https://swiftybeaver.com/. In Vapor 3.0, it includes a simple implementation, PrintLogger for the Logger protocol that prints out logging information on the Terminal screen.
The Logging module is intended to provide logging information while your Vapor app is running. It offers different log levels for you to classify different types of log messages:
Typical Vapor Logger usage looks like this:
let logger = try container.make(Logger.self)
logger.info("Logger created!")
You can get an instance of Logger from any container in Vapor. A container in Vapor refers to a collection of registered services on an event loop and which are prescribed with specific configurations and environments.
Some common containers are application, request, and response. For example, you can get a Logger instance from Application:
let logger = try app.make(Logger.self)
Where app is an instance of your application.