dtp791357 2016-09-24 15:03
浏览 108
已采纳

停止将日志追加到go.log文件中

I have deployed my Go application on Openshift using the Go 1.5.2 cartridge. As a good practice, I have made it a habit to generate logs about anything that goes down with the application. But this habit is proving to be costly in the Openshift environment because of the limited storage (1 GB) provided to me. The logs are easily exceeding the 10 MB mark within a few second of usage, and I fear my application will run out of space if I leave the log file unadministered. Currently, I am clearing the log file manually after regular intervals.

Is there any way I could stop the appending of logs onto the file, or maybe stop the generation of logs altogether (without affecting my original application code)? I have tried by revoking write privileges from the file, but the logs keep appearing anyways.

  • 写回答

1条回答 默认 最新

  • doubu2730 2016-09-24 18:50
    关注

    Ideally, you would want to use a logger that facilitates log levels. This would allow you to adjust the verbosity of logs based on the current runtime context. You can look at the How to implement level based logging in golang question for a wealth of information and packages to facilitate log levels. As a developer, you can include INFO and DEBUG logging statements which, when deployed with a lower log level, will not be included in your logging output.

    If your in a pinch and need to disable the logging in your current implementation you can configure the native go Logger output writer using the SetOutput(output io.Writer) function. The default Writer used by the log package is STDERR. The ioutil package provides a top level Discard Writer that you can use to prevent the logger from writing anything. You would have to update your application initialization to set the output of the logger based on the environment.

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
    )
    
    func main() {
        var shouldEnableLogging bool = false
    
        if !shouldEnableLogging {
            fmt.Println("Disabled logging")
            log.SetOutput(ioutil.Discard)
        }
    
        for i := 0; i < 5; i++ {
            log.Printf("I logging statement %d", i)
        }
    }
    

    You can adjust the bool flag in this snippet to see this in action at this code in the Go Playground. This will prevent your file space from filling up with logs, but you will loose all logs all together which is not advisable for any application.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏