zoukankan      html  css  js  c++  java
  • golang写日志函数

    
    package common
    
    import (
    	"bufio"
    	"fmt"
    	"os"
    	"time"
    )
    
    
    /*自定义日志文件*/
    func DebugLog(args ...interface{}) error {
    	var floderLog = "logs"
    	logName := floderLog + "/debug_log." + time.Now().Format("2006-01-02") + ".log"
    	if _, err := os.Stat(floderLog); err != nil {
    		if !os.IsExist(err) {
    			os.MkdirAll(floderLog, os.ModePerm)
    		}
    	}
    
    	logFile, err := os.OpenFile(logName, os.O_APPEND|os.O_RDWR|os.O_CREATE, os.ModePerm)
    	if err != nil {
    		fmt.Print("打开文件失败")
    		return err
    	}
    	defer logFile.Close()
    	tm := time.Now().Format("2006-01-02 15:04:05")
    	logBody := fmt.Sprintf("%s star============================================>
    ", tm)
    	logFile.WriteString(logBody)
    	logBody = fmt.Sprintf("%+v
    ", args)
    	logFile.WriteString(logBody)
    	logBody = fmt.Sprintf("
    ")
    	logFile.WriteString(logBody)
    	return nil
    }
    
    //DebugLog2 自定义日志文件
    /*
    * dir 文件夹名字
    * fileName 文件名字
    * args 要写入的数据
     */
    func Log(dir string, fileName string, args ...interface{}) error {
    	var floderLog = "logs"
    	if fileName != "" {
    		floderLog = floderLog + "/" + dir
    	}
    	logName := floderLog + "/" + fileName + time.Now().Format("2006-01-02") + ".log"
    	if _, err := os.Stat(floderLog); err != nil {
    		if !os.IsExist(err) {
    			os.MkdirAll(floderLog, os.ModePerm)
    		}
    	}
    
    	logFile, err := os.OpenFile(logName, os.O_APPEND|os.O_RDWR|os.O_CREATE, os.ModePerm)
    	if err != nil {
    		fmt.Println("打开文件失败 err:", err)
    		return err
    	}
    	defer logFile.Close()
    	tm := time.Now().Format("2006-01-02 15:04:05")
    
    	//方法一:os包
    	// logBody := fmt.Sprintf("%s star============================================>
    ", tm)
    	// logFile.WriteString(logBody)
    	// logBody = fmt.Sprintf("%+v
    ", args)
    	// logFile.WriteString(logBody)
    	// logBody = fmt.Sprintf("
    ")
    	// logFile.WriteString(logBody)
    
    	//方法二:bufio包
    	writer := bufio.NewWriter(logFile)
    	logBody := fmt.Sprintf("%s star============================================>
    ", tm)
    	writer.WriteString(logBody) //写入缓存
    	logBody = fmt.Sprintf("%+v
    ", args)
    	writer.WriteString(logBody)
    	logBody = fmt.Sprintf("
    ")
    	writer.WriteString(logBody)
    
    	writer.Flush() //从缓存写入文件
    	return nil
    }
    
    
  • 相关阅读:
    使用jxl.jar操作Excel
    ThreadLocal学习
    ArrayList与Vector、HashMap与HashTable
    String, StringBuffer, StringBuilder比较
    ArrayList与LinkedList实现比较
    Java文件备份类
    Maven安装与更新
    Eclipse安装反编译工具JadClipse
    Linux关闭防火墙
    Hadoop简介
  • 原文地址:https://www.cnblogs.com/haima/p/14004745.html
Copyright © 2011-2022 走看看