import time


def ParseLogEntry(entry):
  """Parses a single log entry emitted by app_logging.AppLogsHandler.

  Parses a log entry of the form LOG <level> <timestamp> <message> where the
  level is in the range [0, 4]. If the entry is not of that form, take the whole
  entry to be the message. Null characters in the entry are replaced by
  newlines.

  Args:
    entry: The log entry to parse.

  Returns:
    A (timestamp, level, message) tuple.
  """
  split = entry.split(' ', 3)
  if len(split) == 4 and split[0] == 'LOG':
    level = split[1]
    timestamp = split[2]
    message = split[3]
    try:
      message = str(message)
      timestamp = int(timestamp)
      level = int(level)
    except ValueError:
      pass
    else:
      if 0 <= level <= 4:
        return timestamp, level, message.replace('\0', '\n')
  usec = int(time.time() * 1e6)
  return usec, 3, entry.replace('\0', '\n')