pythonpython-3.xloggingloguru

python loguru output to stderr and a file


I have the following line that configures my logger instance

logger.add(sys.stderr, level=log_level, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>", colorize=True, backtrace=True, diagnose=True)

I want to configure my logger to use the above, and also output to a file, so that when I call logger.whatever() it outputs to the terminal and to a log file

This way, if I'm doing dev work and running the file directly, I can see the output in my terminal, and when the code is being run on a server by a cronjob, it can log to a file

I don't understand the whole concept of the "sinks" so sorry if this is an easy question


Solution

  • In the context of logging, a "sink" refers to an output destination for log records. It can be a stream (such as sys.stderr or sys.stdout), a file path, or any custom function that accepts the logged message an input. See documentation for more details.

    Using Loguru, you can add as many sinks as you like. This means that in your case, you can have two sinks: one writing to sys.stderr and another one writing to file.log.

    log_level = "DEBUG"
    log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>"
    logger.add(sys.stderr, level=log_level, format=log_format, colorize=True, backtrace=True, diagnose=True)
    logger.add("file.log", level=log_level, format=log_format, colorize=False, backtrace=True, diagnose=True)
    

    Each time a message is logged with logger.info() for example, it will be sent to each of the added sinks and processed based on the the corresponding configuration.