-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
A new log formatter is introduced that adds program contex to the log output, e.g. source file, and line of code where a log call is made. Additional program context can be added consistently. Datetime is formatted in ISO format and an option is provided to use UTC or local timezones.
- Loading branch information
1 parent
7cd90a4
commit b27db87
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package logformatter | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"os" | ||
"time" | ||
) | ||
|
||
type LogWriter struct { | ||
Appname string | ||
UTC bool | ||
} | ||
|
||
const logTimeFormat = "2006-01-02 15:04:05" | ||
|
||
// Write enables us to format a logging prefix for the application. The | ||
// text will appear before the log message output by the caller. | ||
// | ||
// e.g. | ||
// | ||
// `// 2023-11-27 11:36:57 ERROR :: golang-app:100:main() :: this is an error message, ...some diagnosis` | ||
func (lw *LogWriter) Write(logString []byte) (int, error) { | ||
logTime := time.Now().UTC().Format(logTimeFormat) | ||
if !lw.UTC { | ||
logTime = time.Now().Format(logTimeFormat) | ||
} | ||
return fmt.Fprintf(os.Stderr, "%s :: %s :: %s", | ||
logTime, | ||
lw.Appname, | ||
string(logString), | ||
) | ||
} | ||
|
||
func init() { | ||
// Configure logging to use a custom log writer with sensible defaults. | ||
log.SetFlags(0 | log.Lshortfile | log.LUTC) | ||
log.SetOutput(new(LogWriter)) | ||
} |