Show HN: TimeBasedLogger – Python Logger That Logs Based on Time

3 months ago 8

PyPI version Build Status  MIT Python Versions

A Python logger that only logs messages at a specified time interval.


🚀 Production-Grade Features

  • Log Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL, with filtering and convenience methods.
  • Log Formatting: Customizable log message format (default: [{{level}}] {{asctime}} {{message}}).
  • Exception Logging: Log exceptions with stack traces using exc_info=True.
  • Structured/Extra Data: Add extra fields to log records for structured logging.

Inspiration & Acknowledgement

This project was inspired by the article Log by Time, not by Count by John Scolaro. Highly recommended for anyone interested in effective logging strategies in high-frequency systems.

Install from PyPI:

pip install timebased-logger

Or, just copy timebased_logger.py into your project.

  • Log messages only once per specified interval
  • Limit the number of logs per interval (max_logs_per_interval)
  • Pause and resume logging
  • Custom time function for advanced testing
  • High performance async mode: background logging with batching
  • Thread safety: optional locking for multi-threaded use
  • Log levels, formatting, and exception logging (see below)
from timebased_logger import TimeBasedLogger logger = TimeBasedLogger(interval_seconds=2) logger.log("Hello") logger.log("World") # Will not log if called within 2 seconds
logger = TimeBasedLogger(level='WARNING') logger.info("This will NOT be logged") logger.warning("This will be logged") logger.error("This will also be logged")
logger.debug("Debug message") logger.info("Info message") logger.warning("Warning message") logger.error("Error message") logger.critical("Critical message")
logger = TimeBasedLogger(fmt='[{level}] {asctime} {message}') logger.info("Formatted log message")
try: 1/0 except ZeroDivisionError: logger.error("An error occurred", exc_info=True)
logger = TimeBasedLogger(fmt='[{level}] {user} {message}') logger.info("User logged in", extra={'user': 'alice'})
Read Entire Article