1# Copyright 2016 Google LLC All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Logging handler for Google Container Engine (GKE).
16
17Formats log messages in a JSON format, so that Kubernetes clusters with the
18fluentd Google Cloud plugin installed can format their log messages so that
19metadata such as log level is properly captured.
20"""
21
22import logging.handlers
23import warnings
24
25from google.cloud.logging_v2.handlers._helpers import format_stackdriver_json
26
27_DEPRECATION_MSG = (
28 "ContainerEngineHandler is deprecated. Use StructuredLogHandler instead."
29)
30
31
32class ContainerEngineHandler(logging.StreamHandler):
33 """Handler to format log messages the format expected by GKE fluent.
34
35 This handler is written to format messages for the Google Container Engine
36 (GKE) fluentd plugin, so that metadata such as log level are properly set.
37
38 DEPRECATED: use StructuredLogHandler to write formatted logs to standard out instead.
39 """
40
41 def __init__(self, *, name=None, stream=None):
42 """
43 Args:
44 name (Optional[str]): The name of the custom log in Cloud Logging.
45 stream (Optional[IO]): Stream to be used by the handler.
46
47 """
48 super(ContainerEngineHandler, self).__init__(stream=stream)
49 self.name = name
50 warnings.warn(_DEPRECATION_MSG, DeprecationWarning)
51
52 def format(self, record):
53 """Format the message into JSON expected by fluentd.
54
55 Args:
56 record (logging.LogRecord): The log record.
57
58 Returns:
59 str: A JSON string formatted for GKE fluentd.
60 """
61 message = super(ContainerEngineHandler, self).format(record)
62 return format_stackdriver_json(record, message)