Files
fanqie-go/internal/common/logger.go
T
chenxin 6981148727 🔧 chore: 初始化番茄小说 API 项目结构
新增项目基础框架,包含核心 API 实现、算法模块、HTTP 处理器等完整功能模块
2026-08-28 15:22:22 +08:00

124 lines
2.1 KiB
Go

package common
import (
"fmt"
"log"
"strings"
"time"
)
// LogLevel 日志级别
type LogLevel int
const (
DEBUG LogLevel = iota
INFO
WARNING
ERROR
CRITICAL
)
// Logger 日志器
type Logger struct {
moduleName string
outputLevel LogLevel
}
// NewLogger 创建新的日志器
func NewLogger(moduleName string, outputLevel string, filename string) *Logger {
logger := &Logger{
moduleName: moduleName,
}
// 设置日志级别
switch strings.ToUpper(outputLevel) {
case "DEBUG":
logger.outputLevel = DEBUG
case "INFO":
logger.outputLevel = INFO
case "WARNING":
logger.outputLevel = WARNING
case "ERROR":
logger.outputLevel = ERROR
case "CRITICAL":
logger.outputLevel = CRITICAL
default:
logger.outputLevel = INFO
}
return logger
}
// Debug 调试日志
func (l *Logger) Debug(message string) {
if l.outputLevel <= DEBUG {
l.log("DEBUG", message)
}
}
// Info 信息日志
func (l *Logger) Info(message string) {
if l.outputLevel <= INFO {
l.log("INFO", message)
}
}
// Warning 警告日志
func (l *Logger) Warning(message string) {
if l.outputLevel <= WARNING {
l.log("WARNING", message)
}
}
// Error 错误日志
func (l *Logger) Error(message string) {
if l.outputLevel <= ERROR {
l.log("ERROR", message)
}
}
// Critical 严重错误日志
func (l *Logger) Critical(message string) {
if l.outputLevel <= CRITICAL {
l.log("CRITICAL", message)
}
}
// log 内部日志方法
func (l *Logger) log(level string, message string) {
timestamp := time.Now().Format("2006-01-02 15:04:05")
logMessage := fmt.Sprintf("%s|[%s/%s]|%s",
timestamp, l.moduleName, level, message)
// 控制台输出
fmt.Println(logMessage)
}
// Log 全局日志函数
func Log(moduleName string) *Logger {
return NewLogger(moduleName, "INFO", "")
}
// HighlightError 高亮错误
func HighlightError(err interface{}) string {
return fmt.Sprintf("%v", err)
}
// 全局日志实例
var (
defaultLogger = NewLogger("fanqie", "INFO", "")
)
// LogPrint 打印日志
func LogPrint(args ...interface{}) {
message := fmt.Sprint(args...)
defaultLogger.Info(message)
}
func init() {
// 初始化日志系统
log.SetFlags(log.LstdFlags | log.Lshortfile)
}