go log

go自带log包

/*
golang log example
E-Mail : [email protected]
*/
package main

import (
    "log"
    "os"
)

func main() {
    logFile,err := os.Create("test1.log")
    defer logFile.Close()
    if err != nil {
        log.Fatalln("open file error!")
    }
    logger := log.New(logFile,"[Debug]",log.Ldate | log.Ltime | log.Lshortfile)
    logger.Println("test debug message")
    logger.SetPrefix("[Info]")
    logger.Println("test info message")

}

封装logger 一:

package main

import (
    "log"
    "os"
    "io/ioutil"
    "io"
)

var (
    Trace   *log.Logger // 记录所有日志
    Info    *log.Logger // 重要的信息
    Warning *log.Logger // 需要注意的信息
    Error   *log.Logger // 致命错误
)

func init() {
    file, err := os.OpenFile("file", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalln("Failed to open error log file:", err)
    }

    Trace = log.New(ioutil.Discard, "TRACE: ", log.Ltime|log.Lshortfile)
    Info = log.New(os.Stdout, "Info: ", log.Ltime|log.Lshortfile)
    Warning = log.New(os.Stdout, "Warning: ", log.Ltime|log.Lshortfile)
    Error = log.New(io.MultiWriter(file, os.Stderr),  "Error", log.Ltime|log.Lshortfile)
}

func main() {
    Trace.Println("I have something standard to say")
    Info.Println("Special Information")
    Warning.Println("There is something you need to know about")
    Error.Println("Something has failed")
}

封装logger二:

package main

import (
    "bytes"
    "fmt"
    "log"
    "io"
    "io/ioutil"
    "os"
)
type Logger struct {
    // contains filtered or unexported fields
}
var (
    Trace   *log.Logger
    Info    *log.Logger
    Warning *log.Logger
    Error   *log.Logger
)

func Init( traceHandle io.Writer, infoHandle io.Writer,
    warningHandle io.Writer, errorHandle io.Writer)(Trace,Info,Warning,Error *log.Logger) {
    Trace = log.New(traceHandle,"TRACE: ", log.Ldate|log.Ltime|log.Lshortfile)
    Info = log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
    Warning = log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
    Error = log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
    // Trace.Println("XXXXXXXXXXXX")
    return //Trace,Info,Warning,Error
}

func test_log2(){
    Trace,Info,Warning,Error :=Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
    Trace.Println("I have something standard to say")
    Info.Println("Special Information")
    Warning.Println("There is something you need to know about")
    Error.Println("Something has failed")
}

func test_log1(){
    var buf bytes.Buffer
    logger := log.New(&buf, "logger: ", log.Lshortfile|log.Ldate)
    logger.Print("Hello, log file!")
    fmt.Print(&buf)
}

func main() {

    test_log1()
    test_log2()

}

go 切割日志文件

package main

import (
    "fmt"
    "log"
    "os"
    "time"
)

const (
    BACKUP_COUNT = 5
    MAX_FILE_BYTES = 2 * 1024
)

func doRotate(fPrefix string) {
    for j := BACKUP_COUNT; j >= 1; j-- {
        curFileName := fmt.Sprintf("%s_%d.log",fPrefix,j)
        k := j-1
        preFileName := fmt.Sprintf("%s_%d.log",fPrefix,k)

        if k == 0 {
            preFileName = fmt.Sprintf("%s.log", fPrefix)
        }
        _,err := os.Stat(curFileName)
        if err == nil {
            os.Remove(curFileName)
            fmt.Println("remove : ", curFileName)
        }
        _,err = os.Stat(preFileName)
        if err  == nil {
            fmt.Println("rename : ", preFileName, " => ", curFileName)
            err = os.Rename(preFileName, curFileName)
            if err != nil {
                fmt.Println(err)
            }
        }
    }
}

func NewLogger(fPrefix string) (*log.Logger, *os.File) {
    var logger *log.Logger
    fileName := fmt.Sprintf("%s.log", fPrefix)
    fmt.Println("fileName :", fileName)
    logFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

    if err != nil {
        fmt.Println("open file error!")
    } else {
        logger = log.New(logFile, "[Debug]", log.Ldate|log.Ltime|log.Lshortfile)
    }
    return logger, logFile
}

func logWorker(msgQueue <-chan string) {
    fPrefix := "msg"
    logger, logFile := NewLogger(fPrefix)
    for msg := range msgQueue {
        logger.Println(msg)
        fi, err2 := logFile.Stat()
        if err2 == nil {
            if fi.Size() > MAX_FILE_BYTES {
                logFile.Close()
                doRotate(fPrefix)
                logger,logFile = NewLogger(fPrefix)
            }
        }
    }
    logFile.Close()
}

func main() {
    msgQueue := make(chan string, 1000)
    go logWorker(msgQueue)

    for j := 1; j <= 1000; j++ {
        msgQueue <- fmt.Sprintf("msg_%d", j)
        time.Sleep(1 * time.Second)
    }
    close(msgQueue)
    return
}

原文地址:https://www.cnblogs.com/tigerzhouv587/p/11498630.html

时间: 2024-10-30 04:27:34

go log的相关文章

【转】console.log 用法

转自http://www.cnblogs.com/ctriphire/p/4116207.html 大家都有用过各种类型的浏览器,每种浏览器都有自己的特色,本人拙见,在我用过的浏览器当中,我是最喜欢Chrome的,因为它对于调试脚本及前端设计调试都有它比其它浏览器有过之而无不及的地方.可能大家对console.log会有一定的了解,心里难免会想调试的时候用alert不就行了,干嘛还要用console.log这么一长串的字符串来替代alert输出信息呢,下面我就介绍一些调试的入门技巧,让你爱上co

git日志--log

1. 查找改动某个文件所有的日志 git log --pretty=oneline somefile.java git log --oneline somefile.java git log --pretty=format:"%h %an,%cd : %s" somefile.java 2. 格式化输出,git log --pretty=format:" " 选项 说明 %H 提交对象(commit)的完整哈希字串 %h 提交对象的简短哈希字串 %T 树对象(tre

git log进阶

格式化log输出 oneline --oneline标记将每个commit压缩成一行. 默认情况下显示一个commit ID和commit描述的第一行. 输出如下: 0e25143 Merge branch 'feature' ad8621a Fix a bug in the feature 16b36c6 Add a new feature 23ad9ad Add the initial code base decorate 许多时候知道commit是和哪一个分支或tag关联的是非常有用的.

git查看单个文件log

  git log -p c.txt

游戏log的格式的优化

游戏log是非常关键的,对于追踪bug和查看一些信息,所以游戏里面是大量的log输出,sprintf的格式非常难用,而且对格式有较高的要求. 下面一种优化方案如下: // MVC.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> #include <string> #include <sstream> using namespace std; class EndLogOut

使用方法拦截器MethodInterceptor和AOP统一处理log

对每个接口的请求记录log的方法有很多种,比如用filter.mvc interceptor.method interceptor等.如果需要记录请求消息的payload,前两种不适用.下面介绍第三种的实现方法. 第一步:引入包依赖 <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name=&

对于Android系统Log输出日志的封装LogUtils

MainActivity如下: package cc.cn.logutil; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 对于Android系统Log输出日志的封装LogUtils * 1 可修改LogUtils中的LEVEL值觉得哪些级别的日志可以输出. * 所以方便选择性输出日志或者屏蔽日志输出 * 2 输出的日志除了本想输出的信息外还包含了该日志输出时所属 * 的线程,类,方法名,已经在该方法

ORA-16009 remote archive log destination must be a STANDBY database

ORA-16009错误处理 问题描述: 主备在做Switchover切换时,在切换后的备库报如下错误: Wed Jul 22 04:49:02 2015 Errors in file /u01/app/oracle/admin/orcl/bdump/orcl_arc0_8755.trc: ORA-16009: remote archive log destination must be a STANDBY database 解决办法: 查看主库log_archive_dest_2 参数,结果此参

linux中log文件夹各个log文件内容

/var/log/messages - 包括整体系统信息,其中也包含系统启动期间的日志.此外,mail,cron,daemon,kern和auth等内容也记录在var/log/messages日志中. /var/log/dmesg - 包含内核缓冲信息(kernel ring buffer).在系统启动时,会在屏幕上显示许多与硬件有关的信息.可以用dmesg查看它们. /var/log/auth.log - 包含系统授权信息,包括用户登录和使用的权限机制等. /var/log/boot.log

python 实现 math.log(x,base)

python 用闭包实现math.log(x,base) #!/usr/bin/python3 # -*- coding: utf-8 -*- import sys,math import random import pprint def log(n,d): i = 0 status = 0 while True: if d**i==n: status=1 break elif d**i<n<d**(i+1): break i+=1 def test(level=100): if status