Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change log level at runtime? #425

Closed
mrichman opened this issue Oct 12, 2016 · 3 comments
Closed

Change log level at runtime? #425

mrichman opened this issue Oct 12, 2016 · 3 comments

Comments

@mrichman
Copy link

Can I change the log level at runtime? For example, if I have a flag --debug then set DebugLevel.

I'm using urfave/cli (formerly codegangsta/cli) to access flags.

@tomnz
Copy link

tomnz commented Oct 19, 2016

logrus.SetLevel( ... )

@flowchartsman
Copy link

@mrichman please close this issue as your question has been answered.

@ku9nov
Copy link

ku9nov commented May 9, 2024

The actual answer is correct, but it's not fully formed, which is why there are so many negative reactions to it. So, I think it would be helpful to add a simple example of how this can be used to change the log level at runtime.

package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/sirupsen/logrus"
)

var logLevel string

func init() {
	flag.StringVar(&logLevel, "loglevel", "info", "log level (debug, info, warn, error, fatal, panic)")
	flag.Parse()

	logrus.New()

	level, err := logrus.ParseLevel(logLevel)
	if err != nil {
		fmt.Println("Invalid log level specified:", err)
		os.Exit(1)
	}
	logrus.SetLevel(level)
	logrus.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})
}

func main() {
	logrus.Info("Starting application...")
	logrus.Debug("Debug test")
	logrus.Info("Application finished.")
}

In this case, if we run the application with the info flag, we'll get:

go run ./... -loglevel=info
INFO[2024-05-09T18:39:19+03:00] Starting application...
INFO[2024-05-09T18:39:19+03:00] Application finished.

And if we run it with the debug flag, we'll get:

go run ./... -loglevel=debug
INFO[2024-05-09T18:39:21+03:00] Starting application...
DEBU[2024-05-09T18:39:22+03:00] Debug test
INFO[2024-05-09T18:39:22+03:00] Application finished.

This shows how you can dynamically change the log level when running the application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants