如何在 python 中设置 stackdriver 日志条目的严重性?

How do I set the severity of a stackdriver log entry in python?

所以我正在使用 python google 云日志库的 v1 对 GCP stackdriver 进行一些简单的日志记录(见下文)。我不清楚如何为日志条目设置“严重性”级别。当我按如下方式登录时,严重性当前在 Stackdriver 中显示为“默认”。如何设置严重性?我从文档中不清楚。

import google.cloud.logging as glog1

def do_v1_log():
    # Instantiates a client
    logging_client = glog1.Client()

    # The name of the log to write to
    log_name = 'gregs-log'
    # Selects the log to write to
    logger = logging_client.logger(log_name)
    
    # Writes the log entry
    logger.log_struct({'name': 'Greg', 'phone': '619-555-1809'})


# Main bootstrapping routine
if __name__ == "__main__":
    # main()
    do_v1_log()

您可以在日志条目中设置严重性:

LogEntry

Python Client for Stackdriver Logging¶

severity enum (LogSeverity)

Optional. The severity of the log entry. The default value is LogSeverity.DEFAULT.


from google.cloud import logging_v2
client = logging_v2.LoggingServiceV2Client()

resource = {
    "type": "global",
    "labels": {
        "project_id": "[PROJECT_ID]"
    }
}


e = logging_v2.types.LogEntry(
    log_name="projects/[PROJECT_ID]/logs/test-logging", # optional
    resource=resource, # optional
    text_payload="this is a log statement",
    severity="WARNING")

entries = [e]
response = client.write_log_entries(entries)

Writing log entries的另一个例子

def write_entry(logger_name):
    """Writes log entries to the given logger."""
    logging_client = logging.Client()

    # This log can be found in the Cloud Logging console under 'Custom Logs'.
    logger = logging_client.logger(logger_name)

    # Make a simple text log
    logger.log_text('Hello, world!')

    # Simple text log with severity.
    logger.log_text('Goodbye, world!', severity='ERROR')

    # Struct log. The struct can be any JSON-serializable dictionary.
    logger.log_struct({
        'name': 'King Arthur',
        'quest': 'Find the Holy Grail',
        'favorite_color': 'Blue'
    })

    print('Wrote logs to {}.'.format(logger.name))