Use loggers
With gosoline, there are multiple ways to configure and use a logger.
Implement a logger directly in code
One way to implement a logger is using log functions, without appealing to an external configuration:
main.go
package main
import (
"os"
// 1
"github.com/justtrackio/gosoline/pkg/log"
)
func main() {
// 2
logHandler := log.NewHandlerIoWriter(
log.LevelInfo, []string{}, log.FormatterConsole, "", os.Stdout,
)
// 3
loggerOptions := []log.Option{log.WithHandlers(logHandler)}
// 4
logger := log.NewLogger()
// 5
if err := logger.Option(loggerOptions...); err != nil {
logger.Error("Failed to apply logger options: %w", err)
os.Exit(1)
}
logger.Info("Message")
}
Here, you:
- Import the
cfg
package. - Create a new handler for sending logs to STDOUT.
- Create a log option that includes your handler.
- Create your logger.
- Apply the options.
Implement a logger with an app configuration
If you have an application, you can create a logger from your app's configuration.
First, configure your logger in your configuration. For example, in a config file:
config.dist.yml
env: dev
app_project: gosoline
app_family: get-started
app_group: grp
app_name: hello-world
log:
level: info
handlers:
main:
type: iowriter
channels: []
formatter: console
level: info
timestamp_format: 15:04:05.000
writer: stdout
Then, implement your logger alongside your application:
main.go
package main
import (
"context"
"github.com/justtrackio/gosoline/pkg/application"
"github.com/justtrackio/gosoline/pkg/cfg"
"github.com/justtrackio/gosoline/pkg/kernel"
"github.com/justtrackio/gosoline/pkg/log"
)
func NewHelloWorldModule(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {
return &HelloWorldModule{
logger: logger.WithChannel("hello-world"),
}, nil
}
type HelloWorldModule struct {
logger log.Logger
}
func (h HelloWorldModule) Run(ctx context.Context) error {
h.logger.Info("Hello World")
return nil
}
func main() {
application.Run(
application.WithModuleFactory("hello-world", NewHelloWorldModule),
)
}
Conclusion
In this guide, you've learned multiple ways to implement a logger with gosoline.
Check out these resources to learn more about logging with gosoline: