如何在python中设置堆栈驱动程序日志条目的严重性?

时间:2020-10-07 19:53:03

标签: python-3.x google-cloud-platform google-cloud-logging

因此,我正在使用python google cloud日志记录库的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()

1 个答案:

答案 0 :(得分:1)

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

LogEntry

Python Client for Stackdriver Logging¶

严重性枚举(LogSeverity)

可选。日志条目的严重性。默认值为 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))