3 # Copyright 2007 Google Inc.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
19 """Utility methods for working with logs."""
28 REQUEST_LOG_ID
= 'REQUEST_LOG_ID'
37 LOG_LEVEL_CRITICAL
= 4
39 LOG_LEVELS
= [LOG_LEVEL_DEBUG
,
47 _DEFAULT_LEVEL
= LOG_LEVEL_ERROR
50 def _CurrentTimeMicro():
51 return int(time
.time() * _U_SEC
)
55 return e
.replace('\0', '\n')
59 """Returns the ID of the current request assigned by App Engine."""
60 return os
.environ
.get(REQUEST_LOG_ID
, None)
63 def _StrictParseLogEntry(entry
):
64 """Parses a single log entry emitted by app_logging.AppLogsHandler.
66 Parses a log entry of the form LOG <level> <timestamp> <message> where the
67 level is in the range [0, 4]. If the entry is not of that form, ValueError is
71 entry: The log entry to parse.
74 A (timestamp, level, message) tuple.
77 ValueError: if the entry failed to be parsed.
79 magic
, level
, timestamp
, message
= entry
.split(' ', 3)
83 timestamp
, level
= int(timestamp
), int(level
)
84 if level
not in LOG_LEVELS
:
87 return timestamp
, level
, _Clean(message
)
90 def ParseLogEntry(entry
):
91 """Parses a single log entry emitted by app_logging.AppLogsHandler.
93 Parses a log entry of the form LOG <level> <timestamp> <message> where the
94 level is in the range [0, 4]. If the entry is not of that form, take the whole
95 entry to be the message. Null characters in the entry are replaced by
99 entry: The log entry to parse.
102 A (timestamp, level, message) tuple.
105 return _StrictParseLogEntry(entry
)
108 return _CurrentTimeMicro(), _DEFAULT_LEVEL
, _Clean(entry
)
112 """Parses a str containing newline separated log entries.
114 Parses a series of log entries in the form LOG <level> <timestamp> <message>
115 where the level is in the range [0, 4]. Null characters in the entry are
116 replaced by newlines.
119 logs: A string containing the log entries.
122 A list of (timestamp, level, message) tuples.
124 return [ParseLogEntry(line
) for line
in logs
.split('\n') if line
]