Ben Chuanlong Du's Blog

It is never too late to learn.

Python Logging Made Stupidly Simple With Loguru

The best logging package for Python!

  1. Note that the default logging level is DEBUG in loguru and it is not allowed to change the logging level of an created logger object in loguru. You can refer to changing-the-level-of-an-existing-handler and Change level of default handler on ways to changing logging level in loguru.

    1. Remove the default logger (with logging level equals DEBUG) and add a new one with the desired logging level.
    2. Configure the environment variable LOGURU_LEVEL.
  2. Log an exception using luguru and then throws an exception without logging redundant error messages.

     :::python
     def throw(_, error, message, *args, **kwargs):
         message = message.format(*args, **kwargs)
         logger.opt(depth=1).error(message)
         raise error(message)
    
     logger.__class__.throw = throw
    
     logger.throw(ValueError, "Something bad happened")
    
    

    Or if you do not care what kind of exception is thrown to user, you can use the following way which is more concise.

     :::python
     logger.error(message)
     sys.exit()
In [ ]:
 

Comments