123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- /*
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
- package internal
- import (
- "log"
- "os"
- )
- type LogLevel int
- const (
- LogLevelSilent LogLevel = iota - 4
- LogLevelFatal
- LogLevelError
- LogLevelWarn
- LogLevelPrint
- LogLevelInfo
- LogLevelDebug
- )
- func NewLogger() *Logger {
- return &Logger{}
- }
- // TODO use separate debug logger with line number output
- type Logger struct {
- parent *Logger
- level LogLevel
- base string
- }
- func (l *Logger) addBase(format string) string {
- if l.parent == nil {
- return format
- }
- return l.parent.addBase(format)
- }
- func (l *Logger) Level(level LogLevel) {
- l.level = level
- }
- func (l *Logger) Push(str string) *Logger {
- return &Logger{parent: l, base: str}
- }
- func (l *Logger) Print(format string, msg ...any) {
- l.logAs(LogLevelPrint, format, msg...)
- }
- func (l *Logger) Fatal(format string, msg ...any) {
- l.logAs(LogLevelFatal, l.addBase(format), msg...)
- os.Exit(1)
- }
- func (l *Logger) Error(format string, msg ...any) {
- l.logAs(LogLevelError, l.addBase(format), msg...)
- }
- func (l *Logger) Warn(format string, msg ...any) {
- l.logAs(LogLevelWarn, l.addBase(format), msg...)
- }
- func (l *Logger) Info(format string, msg ...any) {
- l.logAs(LogLevelInfo, l.addBase(format), msg...)
- }
- func (l *Logger) Debug(format string, msg ...any) {
- l.logAs(LogLevelDebug, l.addBase(format), msg...)
- }
- func (l *Logger) logAs(
- level LogLevel,
- format string,
- msg ...any,
- ) {
- if level > l.level {
- return
- }
- var pfx string
- switch level {
- case LogLevelFatal:
- pfx = "FATAL"
- case LogLevelError:
- pfx = "ERROR"
- case LogLevelWarn:
- pfx = "Warn"
- case LogLevelInfo:
- pfx = "info"
- case LogLevelDebug:
- pfx = "debug"
- }
- log.Printf(pfx+": "+format, msg...)
- }
|