You can download this code by clicking the button below.
This code is now available for download.
This function uses the Loguru library to generate and log random log messages. It randomly selects a log level and a message template, then fills in the placeholders with random values, and finally outputs the message using Loguru's logging functionality.
Technology Stack : Loguru
Code Type : Function
Code Difficulty : Intermediate
import random
import loguru
from loguru import logger
def random_log_message():
"""
This function generates a random log message and logs it using the Loguru library.
"""
# List of possible log levels
log_levels = ["info", "debug", "warning", "error", "critical"]
# Randomly select a log level
log_level = random.choice(log_levels)
# Randomly select a message template
message_templates = [
"User {user} has logged in.",
"Database connection failed.",
"File {file} has been processed.",
"Error occurred: {error}",
"System is restarting."
]
# Randomly select a message template and fill in the placeholders with random values
message = random.choice(message_templates)
user = random.choice(["Alice", "Bob", "Charlie"])
file = random.choice(["report.txt", "data.csv", "config.yml"])
error = random.choice(["timeout", "database error", "file not found", "network error"])
# Log the message using the selected log level
logger.log(log_level, message.format(user=user, file=file, error=error))
# Example usage
random_log_message()