Disable Log Output During Tests

· 198 words · 1 minute read

It's quite common to use the log package within your code to keep track of things which the end user might not need to see, like deprecated notices and warnings. These are great when they are in production and you are monitoring the logs - but they will show up during your tests.

Below is an example test for our example application (even further below) which just asserts that the result of the function is 5. But this same function call also uses log.

To disregard the logs for these tests we use the TestMain function, set the logging output to discard then run our tests by calling run.

package main

import (

// Importantly you need to call Run() once you've done what you need
func TestMain(m *testing.M) {

func TestDoAndLogSomething(t *testing.T) {
  // Basic Test Example
  if result := DoAndLogSomething(); result != 5 {
    t.Errorf("TestDoAndLogSomething returned an unexpected number: got %v want %v", result, 5)

Our Example Application:

package main

import "log"

func main() {

func DoAndLogSomething() int {
  log.Println("Hello GoLangCode.com")
  return 5

Screenshot of without and with the discard option:

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!