Go-简单日志记录

  • A+
所属分类:阁主小札
package xlog

/*
@author: 晓影
@verson: 2.0
@time: 2019/01/09
*/
import (
	"fmt"
	"os"
	"runtime"
	"sync"
	"time"
)

/*Logger 文件日志*/
type Logger struct {
	file         *os.File
	os           string //操作系统
	SyncToStdOut bool   //是否同步输出到标准输出设备
	sync.Mutex          //写锁
}

/*NewLogger 新建日志记录器*/
func NewLogger(path string, syncToStdOut bool) (*Logger, error) {
	var logger *Logger
	logger = new(Logger)
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) //读写、无则创建、有则清空内容
	logger.file = file
	logger.os = runtime.GOOS
	logger.SyncToStdOut = syncToStdOut
	return logger, err
}

/*Close 关闭日志文件*/
func (logger *Logger) Close() error {
	return logger.file.Close()
}

/*SetFile 更换日志输出文件*/
func (logger *Logger) SetFile(path string) error {
	logger.Lock()
	defer logger.Unlock()
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) //读写、无则创建、有则清空内容
	if err != nil {
		return err
	}
	logger.file = file
	return nil
}

/*Info 信息级日志*/
func (logger *Logger) Info(data ...interface{}) {

	timeNow := time.Now()
	sTime := timeNow.Format("2006/01/02 15:04:05.006")
	logger.Lock()
	defer logger.Unlock()
	if logger.os == "windows" {
		fmt.Fprintf(logger.file, "%s [I] %v%s", sTime, fmt.Sprint(data...), "\r\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [I] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	} else {
		fmt.Fprintf(logger.file, "%s [I] %v%s", sTime, fmt.Sprint(data...), "\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [I] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	}

}

/*Warn 警告级日志*/
func (logger *Logger) Warn(data ...interface{}) {

	timeNow := time.Now()
	sTime := timeNow.Format("2006/01/02 15:04:05.006")
	logger.Lock()
	defer logger.Unlock()
	if logger.os == "windows" {
		fmt.Fprintf(logger.file, "%s [W] %v%s", sTime, fmt.Sprint(data...), "\r\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [W] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	} else {
		fmt.Fprintf(logger.file, "%s [W] %v%s", sTime, fmt.Sprint(data...), "\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [W] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	}

}

/*Error 错误级日志*/
func (logger *Logger) Error(data ...interface{}) {

	timeNow := time.Now()
	sTime := timeNow.Format("2006/01/02 15:04:05.006")
	logger.Lock()
	defer logger.Unlock()
	if logger.os == "windows" {
		fmt.Fprintf(logger.file, "%s [E] %v%s", sTime, fmt.Sprint(data...), "\r\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [E] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	} else {
		fmt.Fprintf(logger.file, "%s [E] %v%s", sTime, fmt.Sprint(data...), "\n")
		if logger.SyncToStdOut {
			fmt.Fprintf(os.Stdout, "%s [E] %v%s", sTime, fmt.Sprint(data...), "\n")
		}
	}

}

weinxin
画麟阁QQ群
这是一个有爱的大家庭,也是东阁唯一的社区,快来和大家一起闲聊、讨论吧!
谷雨

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: