question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Changing format of handler

See original GitHub issue

It appears that you cannot change the format (easily), but have to start a new logger/sink for it (and then stop the previous one), or am I missing something?

I think it would be good to have a method to update the format of a handler (which would take care of handling caches etc) maybe.

Currently I am using:

log_format = loguru._defaults.LOGURU_FORMAT + ' ({extra[reqid]}:{extra[ip]}:{extra[user]})'
logger = loguru.logger
logger.start(sys.stderr, format=log_format)
logger = logger.bind(reqid='-', ip='-', user="-")
logger.stop(0)

And then later bind extra per request:

def get_logger_for_request(request):
    global request_id
    request_id += 1
    ip = request.headers.get("x-real-ip", "?")
    return logger.bind(reqid=request_id, ip=ip, user="?")

Something like logger._handlers[0].set_format(loguru._defaults.LOGURU_FORMAT + ' ({extra[reqid]}:{extra[ip]}:{extra[user]})') could replace the first block here.

I’ve found that there is Handler.update_format, which looked promising, but then it is only about updating formats for color.

Another way would be to use LOGURU_AUTOINIT=0, but I wonder what you think about changing the format on the fly.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
Delgancommented, Dec 15, 2018

@jcmcken The underlying datetime object is indeed timezone aware.

Moreover, when using "{time}" in your format, the timezone offset will be part of the formatted datetime.

logger.remove()
logger.add(sys.stderr, format="{time} - {message}")
logger.info("Test")
# => '2018-12-15T09:06:12.354664+0100 - Test'

You don’t see that in the demonstration gif because I chosen to not use ISO8601 for the default logger format in order to reduce verbosity. The default logger format is more like format="{time:YYYY-MM-DD HH:mm:ss.SSS} {message}", it’s just the local time naively displayed.

There are two things to distinguish: the default time format and the default logger format.

If you want to display timezone by default, you can set the LOGURU_FORMAT environment variable to the format you would prefer, like for example "<g>{time}</g> {level} <lvl>{message}</lvl>". See also the tokens available for datetime formatting.

1reaction
blueyedcommented, Jan 19, 2019

@Delgan Thanks for your help, I am the following in a log module, where I import logger from across the app:

import sys

import loguru

# log_format = '<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level> ({extra})'
log_format = loguru._defaults.LOGURU_FORMAT + ' ({extra[reqid]}:{extra[ip]}:{extra[user]})'

logger = loguru.logger

logger.configure(
    handlers=[
        {"sink": sys.stderr, "format": log_format},
    ],
    extra={"reqid": "-", "ip": "-", "user": "-"},
)
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to change the format of logged messages temporarily, in ...
Here is a simple solution, that can be deduced from Vinay Sajip's own HOWTO; it basically updates the logging formatter with setFormatter() :...
Read more >
Logging Cookbook — Python 3.11.1 documentation
StreamHandler() console. setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging. Formatter('%(name)-12s: %(levelname)-8s %( ...
Read more >
Python Logging Guide - Best Practices and Hands-on Examples
Clients can retrieve and change the threshold logging level of a ... While processing the log records, handlers format log records into log ......
Read more >
Logger - loguru documentation - Read the Docs
Handler ) – An object in charge of receiving formatted logging messages and propagating ... Doing so will convert the datetime to UTC...
Read more >
12.3. Logging Configuration in the CLI
Replace HANDLER with the name of the console log handler. Replace FORMAT with the required formatter string.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found