Logging
Logging is a crucial aspect of every production web application. It helps developers and operations spot bugs, identify performance problems, and analyze outages and security incidents. The data logged depends on the application, typically including the timestamp, log levels (debug, error, info), and contextual information for easy understanding and reproduction.
Base on sirupsen/logrus: Structured, pluggable logging for Go. (github.com)
What to log
It is important to log relevant information for effective logging. Commonly logged data includes:
Timestamp: Indicates when an event occurred or a log was generated.
Log levels: Debug, error, or info levels to categorize the log messages.
Contextual data: Additional information that helps understand the situation and reproduce it easily.
What not to log
In general, you shouldn't log any form of sensitive business data or personally identifiable information. This includes, but is not limited to:
- Password
- Credit card numbers
These restrictions can make logs less useful from an engineering perspective, but they make your application more secure. In many cases, regulations such as GDPR and HIPAA may forbid the logging of personal data.
Functions
// ILogger is an interface for a logger utility.
type ILogger interface {
// Info logs information level messages.
Info(args ...interface{})
// Warn logs warning level messages.
Warn(args ...interface{})
// Debug logs debug level messages.
Debug(args ...interface{})
// Error logs error level messages with an error object.
Error(message error, args ...interface{})
}
Example
package services
import (
"fmt"
core "gitlab.finema.co/finema/idin-core"
)
type userService struct {
ctx core.IContext
}
func (s userService) SomeFunc() (*models.User, core.IError) {
// Log an information message
s.ctx.Log().Info("This is an information message", "more data", 99)
// Log a warning message
s.ctx.Log().Warn("This is a warning message")
// Log a debug message
s.ctx.Log().Debug("This is a debug message")
// Log an error message
err := fmt.Errorf("An error occurred")
s.ctx.Log().Error(err, "This is an error message")
return nil, nil
}
Send to sentry
Update the .env file:
SENTRY_DSN=https://[email protected]/xxxx
Will automatically send to sentry when Error
is called.
Send to graylog
Update the .env file:
LOG_LEVEL=debug|info|warn|error
LOG_HOST=<graylog_ip>
LOG_PORT=<graylog_udp_port>
Set the LOG_LEVEL
variable to one of the following options: debug
, info
, warn
, or error
. This determines the level of logging that will be sent to Graylog. Choose the appropriate level based on the desired verbosity of the logs.