Using Loguru for Simplified and Powerful Python Logging
This article introduces the Loguru library as an elegant, concise alternative to Python's built‑in logging, demonstrating installation, basic usage, file configuration, formatting, filtering, rotation, retention, compression, serialization, and advanced exception tracing with code examples.
Installation
Install Loguru via pip for Python 3: pip3 install loguru .
Basic Usage
Import the pre‑instantiated logger and call its level methods directly:
<code>from loguru import logger
logger.debug('This is debug information')
logger.info('This is info information')
logger.warning('This is warn information')
logger.error('This is error information')</code>Loguru automatically adds timestamps, level, module name, line number, and colors the output.
Loguru File Configuration
Use logger.add() to add a file sink with optional rotation, retention, encoding, and queueing:
<code>from loguru import logger
logger.add("E:/PythonCode/MOC/log_2021-3-28.log", rotation="500MB", encoding="utf-8", enqueue=True, retention="10 days")
logger.info('This is info information')</code>String Formatting
Loguru supports f‑string style formatting with keyword arguments:
<code>import platform
from loguru import logger
logger.info('If you are using Python {version}, prefer {feature} of course!', version=platform.python_version(), feature='f-strings')</code>Common Parameters
sink : file path, file‑like object, coroutine, or logging.Handler.
level : minimum severity to record.
format : template for log messages.
filter : callable, string or dict to decide which records are emitted.
colorize : enable/disable ANSI colors.
serialize : output logs as JSON strings.
backtrace : extend traceback beyond the catch point.
diagnose : show variable values in tracebacks.
enqueue : send logs through a multiprocessing‑safe queue.
catch : automatically catch exceptions in the sink.
Stopping Logging to a File
Remove a sink by its identifier returned from add() :
<code>from loguru import logger
trace = logger.add('2021-3-28.log')
logger.error('This is error information')
logger.remove(trace)
logger.warning('This is warn information')</code>Output Only to File (No Console)
Remove the default handler and add a file sink:
<code>from loguru import logger
logger.remove(handler_id=None)
trace = logger.add('2021-3-28.log')
logger.error('This is error information')
logger.warning('This is warn information')</code>Filter Configuration
Define a filter function to keep only ERROR level logs:
<code>from loguru import logger
def error_only(record):
"""Return True only for ERROR level records"""
return record["level"].name == "ERROR"
logger.add('2021-3-28.log', filter=error_only)
logger.error('This is error information')
logger.warning('This is warn information')</code>Format Template
Customise the log line format:
<code>from loguru import logger
def format_log():
trace = logger.add('2021-3-28.log', format="{time:YYYY-MM-DD HH:mm:ss} {level} From {module}.{function} : {message}")
logger.warning('This is warn information')
if __name__ == '__main__':
format_log()
</code>Extra Bind for Structured Logs
Attach additional fields to each record:
<code>from loguru import logger
def format_log():
trace = logger.add('2021-3-28.log', format="{time:YYYY-MM-DD HH:mm:ss} {extra[ip]} {extra[username]} {level} From {module}.{function} : {message}")
extra_logger = logger.bind(ip='192.168.0.1', username='张三')
extra_logger.info('This is info information')
extra_logger.bind(username='李四').error('This is error information')
extra_logger.warning('This is warn information')
if __name__ == '__main__':
format_log()
</code>Level Configuration
<code>from loguru import logger
trace = logger.add('2021-3-29.log', level='ERROR')
</code>Rotation
Rotate logs by size, time of day, or interval:
<code>from loguru import logger
logger.add('2021-3-28.log', rotation='200 MB')
logger.add('2021-3-28.log', rotation='06:00')
logger.add('2021-3-28.log', rotation='2 week')
</code>Retention
Automatically delete logs older than a given period:
<code>from loguru import logger
logger.add('2021-3-28.log', retention='7 days')
</code>Compression
Compress closed log files (e.g., zip):
<code>from loguru import logger
logger.add('2021-3-28.log', compression='zip')
</code>Serialization
Write each log entry as a JSON line for downstream analysis:
<code>from loguru import logger
import platform
rounded_value = round(0.345, 2)
trace = logger.add('2021-3-28.log', serialize=True)
logger.info('If you are using Python {version}, prefer {feature} of course!', version=platform.python_version(), feature='f-strings')
</code>Traceback (Exception Tracing)
Loguru integrates better_exceptions to provide rich tracebacks. Example using the @logger.catch decorator:
<code>from loguru import logger
trace = logger.add('2021-3-28.log')
@logger.catch
def index_error(custom_list: list):
for index in range(len(custom_list)):
index_value = custom_list[index]
if custom_list[index] < 2:
custom_list.remove(index_value)
print(index_value)
if __name__ == '__main__':
index_error([1,2,3])
</code>Exception Logging with logger.exception
<code>from loguru import logger
trace = logger.add('2021-3-28.log')
def index_error(custom_list: list):
for index in range(len(custom_list)):
try:
index_value = custom_list[index]
except IndexError as err:
logger.exception(err)
break
if custom_list[index] < 2:
custom_list.remove(index_value)
if __name__ == '__main__':
index_error([1,2,3])
</code>Class and Static Method Examples
<code>from loguru import logger
trace = logger.add('2021-3-28.log')
class Demo:
@logger.catch
def index_error(self, custom_list: list):
for index in range(len(custom_list)):
index_value = custom_list[index]
if custom_list[index] < 2:
custom_list.remove(index_value)
@staticmethod
@logger.catch
def index_error_static(custom_list: list):
for index in range(len(custom_list)):
index_value = custom_list[index]
if custom_list[index] < 2:
custom_list.remove(index_value)
if __name__ == '__main__':
# Demo().index_error([1, 2, 3])
Demo.index_error_static([1, 2, 3])
</code>Level Name
Severity Value
Logger Method
TRACE
5
logger.trace()
DEBUG
10
logger.debug()
INFO
20
logger.info()
SUCCESS
25
logger.success()
WARNING
30
logger.warning()
ERROR
40
logger.error()
CRITICAL
50
logger.critical()
For a full list of Loguru configuration keys and their meanings, refer to the documentation table included above.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.