略微加速

略速 - 互联网笔记

Beego Log日志模块配置及使用

2021-04-02 leiting (2635阅读)

标签 Golang

由于首次接触beego,在使用log时,

1 目录结构

2 log 配置app.conf

[log]
log_level = 7 //debug级别
log_path = logs/app.log //指定log文件名
maxlines = 10 //log文件最大行数
maxsize = 1024 //log文件大小限制12345

后两项是控制log文件大小的,其中maxlines 超出后会自动生成新的app.log文件,原log文件重命名为app.2020-03-22.001.log,自动实现日志切割

3 log结构封装
log文件在components目录下,logger.go

package components

import (
	"fmt"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/config"
)

func InitLogger() (err error) {
	BConfig, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil{
		fmt.Println("config init error:", err)
		return
	}
	maxlines, lerr := BConfig.Int64("log::maxlines")
	if lerr != nil {
		maxlines = 1000
	}

	logConf := make(map[string]interface{})
	logConf["filename"] = BConfig.String("log::log_path")
	level,_ := BConfig.Int("log::log_level")
	logConf["level"] = level
	logConf["maxlines"] = maxlines
	 
    confStr, err := json.Marshal(logConf)
    if err != nil {
        fmt.Println("marshal failed,err:", err)
        return
	}
	beego.SetLogger(logs.AdapterFile, string(confStr))
	beego.SetLogFuncCall(true)
	return
}

4 注册

package main

import (
	"github.com/astaxie/beego"
	_ "template/routers"
	"template/components"
)

func init() {
	components.InitLogger() //调用logger初始化
	components.InitDB() //db初始化,多db注册
}

func main() {
	beego.Run()
}

5 日志级别及使用

1-7级别递减,默认是trace,显示当前数字以前的级别,例如:3时,显示【Emergency】【Alert】【Critical】【Error】

// RFC5424 log message levels.
const (
	LevelEmergency = iota
	LevelAlert                //1
	LevelCritical	          //2
	LevelError		  //3
	LevelWarning	          //4
	LevelNotice		  //5
	LevelInformational        //6
	LevelDebug		  //7
)
beego.Info("hello world");

打印的日志格式如下
2020/03/22 14:54:07.509 [I] [RuleController.go:16] hello world


参考文档

https://beego.me/docs/module/logs.md



北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3