loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Change the format of the default logger

Open sisibeloved opened this issue 6 years ago • 2 comments

hello, I'm trying to add a request ID in the log message. I've tried the configure function like this:

extra = {"request_id": "default"}
logger.configure(extra=extra)
logger.add(sys.stderr, format="{time} - {extra[request_id]} - {level} - {message}")

And there are two lines of log printed. Then I find in the documentation that the Logger class is already instantiated when import. So I change the code into:

logger.remove(0)
extra = {"request_id": "default"}
logger.configure(extra=extra)
logger.add(sys.stderr, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <yellow>{extra[request_id]}</yellow> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>")

Is there any elegant method to change the format of the default logger or have I used the wrong function?

sisibeloved avatar Jul 23 '20 05:07 sisibeloved

Hi @sisibeloved, your second snippet is the conventional solution. It's not possible to modify a handler once it has been added, so it's not possible to change the format of the default one. If it doesn't suit your preferences, you have to remove it and add a new one just like you did.

If the passed format looks to verbose, note that you can simplify it. For example, <yellow>{extra[request_id]}</yellow> can become <y>{extra[request_id]}</>. See the color markups.

Also, there is a possibility to modify the format of the default handler by using environment variable, see examples. The configured format will automatically be used each time the logger is imported. However, I'm not sure it works well in your case, since you use the extra [request_id] which is specific to your application.

Delgan avatar Jul 23 '20 06:07 Delgan

Thanks for the reply. I'm gonna adopt the second code snippet.

sisibeloved avatar Jul 23 '20 11:07 sisibeloved