All Products
Search
Document Center

Simple Log Service:Collect Python logs

Last Updated:Jul 27, 2023

This topic describes how to use Logtail to collect Python logs.

Background information

The Python logging module provides a general logging system, which can be used by third-party modules or applications. The logging module defines multiple log levels and logging methods. The logging module consists of the following components: loggers, handlers, filters, and formatters.

Formatters specify the output format of logs. The fields that are configured for a formatter are in the %(key)s format. Sample code:

import logging  
import logging.handlers  
LOG_FILE = 'tst.log'  
handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCount = 5) # Create a handler.   
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(levelno)s %(levelname)s %(pathname)s %(module)s %(funcName)s %(created)f %(thread)d %(threadName)s %(process)d %(name)s - %(message)s' // Define the output format of logs. 
formatter = logging.Formatter(fmt)   # Create a formatter.  
handler.setFormatter(formatter)      # Add the formatter to the handler. 
logger = logging.getLogger('tst')    # Retrieve a logger that is named tst.   
logger.addHandler(handler)           # Add the handler to the logger.  
logger.setLevel(logging.DEBUG)  
logger.info('first info message')  
logger.debug('first debug message')

The following table describes the fields in the sample code.

Field

Description

%(name)s

The name of the logger that is used to log the call.

%(levelno)s

The log level in the numeric format.

%(levelname)s

The log level in the text format. Valid values: DEBUG, INFO, WARNING, ERROR, and CRITICAL.

%(pathname)s

The log file path.

%(filename)s

The log file name.

%(module)s

The name of the source module for log collection.

%(funcName)s

The name of the function that contains the logging call.

%(lineno)d

The source line number of the statement that includes the function.

%(created)f

The time at which a log is created. The time is a UNIX timestamp.

%(relativeCreated)d

The difference between the time at which a log is created and the time at which the logging module is loaded. Unit: milliseconds.

%(asctime)s

The time at which a log is created. Example: 2003-07-08 16:49:45,896. The digits after the comma (,) indicate the millisecond portion of the time.

%(msecs)d

The millisecond portion of the time at which a log is generated.

%(thread)d

The thread ID.

%(threadName)s

The thread name.

%(process)d

The process ID.

%(message)s

The log information.

Procedure

Simple Log Service provides configuration wizards to help you create Logtail configurations. The following example describes how to collect Python logs in full regex mode.

  1. Log on to the Log Service console.
  2. In the Import Data section, select RegEx - Text Log.
  3. Select the project and Logstore. Then, click Next.
  4. Create a machine group.
    • If a machine group is available, click Use Existing Machine Groups.
    • If no machine groups are available, perform the following steps to create a machine group. In this example, an Elastic Compute Service (ECS) instance is used.
      1. On the ECS Instances tab, select Manually Select Instances. Then, select the ECS instance that you want to use and click Create.

        For more information, see Install Logtail on ECS instances.

        Important If you want to collect logs from an ECS instance that belongs to a different Alibaba Cloud account than Log Service, a server in a data center, or a server of a third-party cloud service provider, you must manually install Logtail. For more information, see Install Logtail on a Linux server or Install Logtail on a Windows server.

        After you manually install Logtail, you must configure a user identifier for the server. For more information, see Configure a user identifier.

      2. After Logtail is installed, click Complete Installation.
      3. In the Create Machine Group step, configure the Name parameter and click Next.

        Log Service allows you to create IP address-based machine groups and custom identifier-based machine groups. For more information, see Create an IP address-based machine group and Create a custom identifier-based machine group.

  5. Select the new machine group from Source Server Groups and move the machine group to Applied Server Groups. Then, click Next.
    Important If you apply a machine group immediately after you create the machine group, the heartbeat status of the machine group may be FAIL. This issue occurs because the machine group is not connected to Log Service. To resolve this issue, you can click Automatic Retry. If the issue persists, see What do I do if no heartbeat connections are detected on Logtail?
  6. In the Logtail Config step, create a Logtail configuration.

    The following list describes the key parameters that are used to create the Logtail configuration. For more information about other parameters, see Collect logs in full regex mode.

    • Log Sample: 2022-02-19 11:06:52,514 - test.py:19 - 10 DEBUG test.py test <module> 1645240015.514271 139865996687072 MainThread 20193 tst - first debug message

    • RegEx: (\d+-\d+-\d+\s\S+)\s-\s([^:]+):(\d+)\s+-\s+(\d+)\s+(\w+)\s+(\S+)\s+(\w+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+)\s+(\d+)\s+(\w+)\s+-\s+(.*)

    • Extracted Content: Log Service automatically extracts content from logs based on the sample log and regular expression that you specify. You must specify keys for the extracted content.
    Python logs
  7. Preview data, configure indexes, and then click Next.
    By default, full-text indexing is enabled for Log Service. You can also configure field indexes based on collected logs in manual mode or automatic mode. To configure field indexes in automatic mode, click Automatic Index Generation. This way, Log Service automatically creates field indexes. For more information, see Create indexes.
    Important If you want to query and analyze logs, you must enable full-text indexing or field indexing. If you enable both full-text indexing and field indexing, the system uses only field indexes.
  8. Click Log Query. You are redirected to the query and analysis page of your Logstore.
    You must wait approximately 1 minute for the indexes to take effect. Then, you can view the collected logs on the Raw Logs tab. For more information, see Query and analyze logs.