Home  >  Article  >  Backend Development  >  How Do I Disable Logging in Go?

How Do I Disable Logging in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 15:03:02733browse

How Do I Disable Logging in Go?

Disabling Loggers in Go

You're working with code heavily instrumented with Go's logging package. When it's time to turn off logging, you're baffled by the absence of a discernible method to disable the standard logger. Should you set a flag before making log calls or resort to commenting them out in production?

Fear not, there's a solution that avoids the creation of custom io.Writer types and manual flag checking.

Solution

Use io/ioutil.Discard to write to a nothingness io.Writer:

import (
    "log"
    "io/ioutil"
)

func init() {
    log.SetOutput(ioutil.Discard)
}

For Go 1.16 and above, simply use io.Discard:

log.SetOutput(io.Discard)

This effectively disables logging by discarding all log entries. No more arduous flag checking or manual commenting required!

The above is the detailed content of How Do I Disable Logging in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn