import re


def parse_error_message(stderr_data):
  """Parses the stderr data and returns only the message with ERROR level."""
  messages = stderr_data.split("\n")
  result = ""

  # Each line of message should be: date, time, log level, line number, message.
  # E.g. 2017-10-03 18:25:19.742351: E file.cc: xx xxxx.
  # We only want the message with ERROR level.
  pattern = r"(\d+-\d+-\d+) (\d+:\d+:\d+.\d+:) ([EWI]) (\S+) (.*)"
  def _get_log_level_and_message(line):
    match = re.match(pattern, line)
    if match is None:
      return None, line
    else:
      return match.group(3), match.group(5)

  previous_is_error = False
  for message in messages:
    log_level, message_wthout_timestamp = _get_log_level_and_message(message)
    if log_level == "E":
      result += message_wthout_timestamp
      result += "\n"
      previous_is_error = True
    elif log_level == "W" or log_level == "I":
      previous_is_error = False
    else:
      # No log level, part of multiline message.
      if previous_is_error:
        result += message
        result += "\n"
  return result