• golang log


    自带log模块

       写入文件

       

    package main
    
    import (
        "fmt"
        "log"
        "os"
    )
    
    func main(){
        logfile,err := os.OpenFile("d:/test.log",os.O_APPEND|os.O_RDWR|os.O_CREATE,0);
        if err!=nil {
            fmt.Printf("%s
    ",err.Error());
            os.Exit(-1);
        }
        defer logfile.Close();
        logger := log.New(logfile,"
    ",log.Ldate|log.Ltime|log.Llongfile);
        logger.Println("hello");
        logger.Println("oh....");
        logger.Fatal("test");
        logger.Fatal("test2");
    }

     写入文件同时输入到控制台

    package main
    
    import (
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func main() {
        logfile, err := os.OpenFile("d:/test.log", os.O_APPEND|os.O_RDWR|os.O_CREATE, 0777)
        if err != nil {
            fmt.Printf("%s
    ", err.Error())
            os.Exit(-1)
        }
        defer logfile.Close()
        writers := []io.Writer{
            logfile,
            os.Stdout,
        }
        fileAndStdoutWriter := io.MultiWriter(writers...)
        logger := log.New(fileAndStdoutWriter, "
    ", log.Ldate|log.Ltime|log.Llongfile)
        logger.Println("hello")
        logger.Println("oh....")
        logger.Fatal("test")
        logger.Fatal("test2")
    }

    补充:

    Ldate、Ltime等被定义为常量:
    const (
        // Bits or'ed together to control what's printed. There is no control over the
        // order they appear (the order listed here) or the format they present (as
        // described in the comments).  A colon appears after these items:
        //	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
        Ldate         = 1 << iota     // the date: 2009/01/23
        Ltime                         // the time: 01:23:23
        Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
        Llongfile                     // full file name and line number: /a/b/c/d.go:23
        Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
        LstdFlags     = Ldate | Ltime // initial values for the standard logger
    )

    log4go模块

    /*
     * [File]
     * EmulateLoginBaidu.go
     *
     * [Function]
     * 【记录】用go语言实现模拟登陆百度
     * http://www.crifan.com/emulate_login_baidu_using_go_language/
     *
     * [Version]
     * 2013-09-19
     *
     * [Contact]
     * http://www.crifan.com/about/me/
     */
    package main
     
    import (
        //"fmt"
        //"builtin"
        //"log"
        "os"
        "runtime"
        "path"
        "strings"
        //"io"
        "time"
        "io/ioutil"
        "net/http"
        //"net/http/cookiejar"
        //"sync"
        //"net/url"
    )
     
    //import l4g "log4go.googlecode.com/hg"
    //import l4g "code.google.com/p/log4go"
    import "code.google.com/p/log4go"
     
    /***************************************************************************************************
        Global Variables
    ***************************************************************************************************/
    var gCurCookies []*http.Cookie;
    //var gLogger *log.Logger;
    var gLogger log4go.Logger;
     
    /***************************************************************************************************
        Functions
    ***************************************************************************************************/
    //do init before all others
    func initAll(){
        gCurCookies = nil
        gLogger = nil
         
        initLogger()
        initCrifanLib()
    }
     
    //de-init for all
    func deinitAll(){
        gCurCookies = nil
        if(nil == gLogger) {
            gLogger.Close();
            gLogger = nil
        }
    }
     
    //do some init for crifanLib
    func initCrifanLib(){
        gLogger.Debug("init for crifanLib")
        gCurCookies = nil
        return
    }
     
    //init for logger
    func initLogger(){
        var filenameOnly string
        filenameOnly = GetCurFilename()
        var logFilename string =  filenameOnly + ".log";
         
        //gLogger = log4go.NewLogger()
        gLogger = make(log4go.Logger)
        //for console
        //gLogger.AddFilter("stdout", log4go.INFO, log4go.NewConsoleLogWriter())
        gLogger.AddFilter("stdout", log4go.INFO, log4go.NewConsoleLogWriter())
        //for log file
        if _, err := os.Stat(logFilename); err == nil {
            //fmt.Printf("found old log file %s, now remove it
    ", logFilename)
            os.Remove(logFilename)
        }
        //gLogger.AddFilter("logfile", log4go.FINEST, log4go.NewFileLogWriter(logFilename, true))
        gLogger.AddFilter("logfile", log4go.FINEST, log4go.NewFileLogWriter(logFilename, false))
        gLogger.Info("Current time is : %s", time.Now().Format("15:04:05 MST 2006/01/02"))
     
        return
    }
     
    // GetCurFilename
    // Get current file name, without suffix
    func GetCurFilename() string {
        _, fulleFilename, _, _ := runtime.Caller(0)
        //fmt.Println(fulleFilename)
        var filenameWithSuffix string
        filenameWithSuffix = path.Base(fulleFilename)
        //fmt.Println("filenameWithSuffix=", filenameWithSuffix)
        var fileSuffix string
        fileSuffix = path.Ext(filenameWithSuffix)
        //fmt.Println("fileSuffix=", fileSuffix)
         
        var filenameOnly string
        filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
        //fmt.Println("filenameOnly=", filenameOnly)
         
        return filenameOnly
    }
     
    //get url response html
    func GetUrlRespHtml(url string) string{
        gLogger.Debug("GetUrlRespHtml, url=%s", url)
        var respHtml string = "";
         
        resp, err := http.Get(url)
        if err != nil {
            gLogger.Warn("http get url=%s response errror=%s
    ", url, err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        //gLogger.Debug("body=%s
    ", body)
     
        gCurCookies = resp.Cookies()
         
        respHtml = string(body)
     
        return respHtml
    }
     
    func printCurCookies() {
        var cookieNum int = len(gCurCookies);
        gLogger.Info("cookieNum=%d", cookieNum)
        for i := 0; i < cookieNum; i++ {
            var curCk *http.Cookie = gCurCookies[i];
            //gLogger.Info("curCk.Raw=%s", curCk.Raw)
            gLogger.Info("------ Cookie [%d]------", i)
            gLogger.Info("Name	=%s", curCk.Name)
            gLogger.Info("Value	=%s", curCk.Value)
            gLogger.Info("Path	=%s", curCk.Path)
            gLogger.Info("Domain	=%s", curCk.Domain)
            gLogger.Info("Expires	=%s", curCk.Expires)
            gLogger.Info("RawExpires=%s", curCk.RawExpires)
            gLogger.Info("MaxAge	=%d", curCk.MaxAge)
            gLogger.Info("Secure	=%t", curCk.Secure)
            gLogger.Info("HttpOnly=%t", curCk.HttpOnly)
            gLogger.Info("Raw	=%s", curCk.Raw)
            gLogger.Info("Unparsed=%s", curCk.Unparsed)
        }
    }
     
    func main() {
        initAll()
     
        gLogger.Info("this is EmulateLoginBaidu.go")
     
        var baiduMainUrl string
        baiduMainUrl = "http://www.baidu.com/";
        //baiduMainUrl := "http://www.baidu.com/";
        //var baiduMainUrl string = "http://www.baidu.com/";
        gLogger.Info("baiduMainUrl=%s", baiduMainUrl)
        respHtml := GetUrlRespHtml(baiduMainUrl)
        gLogger.Debug("respHtml=%s", respHtml)
        printCurCookies()
         
        deinitAll()
    }

    转自:http://www.crifan.com/go_language_output_log_to_both_file_and_console_meantime_via_log4go/

  • 相关阅读:
    Ubuntu8.04代码已冻结发布在即
    Ruby on rails开发从头来(五十) ActiveRecord基础(更新记录)
    Ruby on rails开发从头来(四十四) ActiveRecord基础(创建记录)
    Ruby on rails开发从头来(四十五) ActiveRecord基础(读取记录)
    网络恶搞“白送家产”:美国男子回家发现财产被搬空
    Ruby on rails开发从头来(四十三) ActiveRecord基础(连接数据库)
    Ruby on rails开发从头来(四十九) ActiveRecord基础(行数和再加载数据)
    Ruby on rails开发从头来(四十七) ActiveRecord基础(强大的find方法)
    Ruby on rails开发从头来(四十六) ActiveRecord基础(SQL和Active Record)
    简单三步堵死SQL Server注入漏洞
  • 原文地址:https://www.cnblogs.com/wangxusummer/p/4064653.html
Copyright © 2020-2023  润新知