杰瑞科技汇

Python writelog如何高效记录日志?

Of course! The term writelog() is not a built-in Python function. It's a common convention for developers to create their own function to write log messages.

Python writelog如何高效记录日志?-图1
(图片来源网络,侵删)

I'll guide you through several ways to implement and use a writelog() function, from a simple custom version to using Python's powerful built-in logging module.


The Simple, Custom writelog() Function

This is the most direct answer to your request. We'll create a function that appends a timestamped message to a log file.

The Code

import datetime
def writelog(message, log_file="app.log"):
    """
    Appends a timestamped message to a log file.
    Args:
        message (str): The message to write to the log.
        log_file (str): The name of the log file. Defaults to "app.log".
    """
    # Get the current time
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # Create the log entry
    log_entry = f"[{timestamp}] - {message}\n"
    # Open the file in append mode ('a') and write the entry
    # The 'with' statement ensures the file is automatically closed
    try:
        with open(log_file, "a") as f:
            f.write(log_entry)
    except Exception as e:
        # Fallback to printing to console if file writing fails
        print(f"Error writing to log file: {e}")
        print(log_entry)
# --- How to Use It ---
# First call
writelog("Application has started.")
# Another call with more detail
writelog("User 'admin' has logged in.")
# Call with a variable
error_message = "Failed to connect to the database."
writelog(error_message)
# Check the contents of "app.log" in your directory
# It will contain:
# [2025-10-27 10:30:00] - Application has started.
# [2025-10-27 10:30:01] - User 'admin' has logged in.
# [2025-10-27 10:30:02] - Failed to connect to the database.

Breakdown of the Simple Function:

  • import datetime: Imports Python's module for handling dates and times.
  • def writelog(message, log_file="app.log"): Defines the function. It accepts a required message and an optional log_file argument with a default value.
  • datetime.datetime.now().strftime(...): Gets the current time and formats it into a YYYY-MM-DD HH:MM:SS string.
  • f"[{timestamp}] - {message}\n": Creates the final log string using an f-string. The \n adds a newline character so each log entry is on its own line.
  • with open(log_file, "a") as f:: This is the standard, safe way to handle files in Python.
    • "a" stands for append mode. If the file doesn't exist, it will be created. If it does exist, new content will be added to the end without deleting the old content.
    • The with statement guarantees that the file is closed properly after the block of code is executed, even if errors occur.
  • f.write(log_entry): Writes the formatted string to the file.
  • try...except: A simple error-handling block. If the program can't write to the file (e.g., due to permissions), it will print an error to the console instead of crashing.

The Better Way: Using Python's logging Module

For any real-world application, you should use Python's built-in logging module. It's more powerful, flexible, and handles many edge cases for you.

The logging module has different levels of severity, which is a key feature.

Python writelog如何高效记录日志?-图2
(图片来源网络,侵删)
Level Numeric Value Use Case
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 An indication that something unexpected happened, or a problem might occur in the near future (e.g., ‘disk space low’). The software is still working as expected.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A very serious error, indicating that the program itself may be unable to continue running.

Example with the logging Module

import logging
# 1. Configure the logging system
# This is the most important step!
logging.basicConfig(
    level=logging.INFO,  # Set the minimum level of messages to log
    format='%(asctime)s - %(levelname)s - %(message)s', # Format of the log message
    filename='app.log',  # File to write logs to
    filemode='a'         # 'a' for append, 'w' for write (overwrite)
)
# 2. Now, you can use the logging functions directly
# There is no need to create your own writelog() function.
logging.info("Application has started.") # An informational message
logging.warning("This is a warning message.") # A warning
logging.error("Failed to connect to the database.") # An error
# You can also pass variables
user = 'test_user'
logging.info(f"User '{user}' has performed an action.")
# If you want to log something only for debugging, you can change the level
# or use the debug function. It won't appear because the level is set to INFO.
logging.debug("This debug message will not be shown in the log file.")
# Check "app.log". It will contain:
# 2025-10-27 10:35:12,123 - INFO - Application has started.
# 2025-10-27 10:35:12,124 - WARNING - This is a warning message.
# 2025-10-27 10:35:12,124 - ERROR - Failed to connect to the database.
# 2025-10-27 10:35:12,125 - INFO - User 'test_user' has performed an action.

Why is the logging module better?

  • Levels: You can easily control the verbosity of your logs. For production, you might set the level to WARNING or ERROR to reduce noise, but for development, you can set it to DEBUG.
  • Flexibility: You can easily configure logs to go to the console, a file, a network socket, or all of them at the same time.
  • Standardization: It's the standard across the Python ecosystem. Other libraries you use (like Flask or Django) will integrate with it seamlessly.
  • Performance: The logging module is highly optimized. For example, if your log level is INFO, any debug() calls are very cheap and don't even format the string, saving CPU cycles.

Creating a writelog() Wrapper for the logging Module

If you still prefer the writelog() function name for your team or project, you can easily create a wrapper around the logging module.

import logging
# Configure logging first
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='app.log',
    filemode='a'
)
# Our custom wrapper function
def writelog(message, level="INFO"):
    """
    A wrapper for the logging module to provide a simple writelog function.
    Args:
        message (str): The message to write.
        level (str): The logging level (e.g., "INFO", "WARNING", "ERROR").
    """
    # Convert the string level to the logging constant
    numeric_level = getattr(logging, level.upper(), None)
    # Check if the level is valid
    if not isinstance(numeric_level, int):
        raise ValueError(f"Invalid log level: {level}")
    # Call the appropriate logging function
    if numeric_level == logging.DEBUG:
        logging.debug(message)
    elif numeric_level == logging.INFO:
        logging.info(message)
    elif numeric_level == logging.WARNING:
        logging.warning(message)
    elif numeric_level == logging.ERROR:
        logging.error(message)
    elif numeric_level == logging.CRITICAL:
        logging.critical(message)
# --- How to Use It ---
writelog("Application started using the wrapper.", "INFO")
writelog("This is a critical error!", "CRITICAL")
writelog("A minor issue occurred.", "WARNING")
# This will raise a ValueError
# writelog("This will fail.", "INVALID_LEVEL")

Summary: Which one should you use?

Method Pros Cons Best For
Simple writelog() Easy to understand and write. Good for very small scripts. Not scalable, no log levels, manual error handling needed. Quick scripts, personal projects, learning.
logging Module Industry standard, powerful, flexible, has levels, handles errors. Requires initial setup (basicConfig). Almost all Python applications, from small to large.
writelog() Wrapper Keeps a familiar API while leveraging the power of logging. Adds a thin layer of abstraction. Projects where a team prefers a custom function name.

Recommendation: For any serious project, always use the built-in logging module. It's a best practice that will save you time and headaches in the long run. The simple custom function is fine for a quick, one-off script, but the logging module is the right tool for the job.

Python writelog如何高效记录日志?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇