Skip to content

Commit

Permalink
Set log time format (#1737)
Browse files Browse the repository at this point in the history
* Modified log time format
  • Loading branch information
larohra authored Dec 16, 2019
1 parent 44d4de1 commit 435dd44
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion azurelinuxagent/common/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def write_log(log_appender):
else:
msg = msg_format
# This format is based on ISO-8601, Z represents UTC (Zero offset)
time = datetime.utcnow().isoformat() + "Z"
time = datetime.utcnow().strftime(u'%Y-%m-%dT%H:%M:%S.%fZ')
level_str = LogLevel.STRINGS[level]
if self.prefix is not None:
log_item = u"{0} {1} {2} {3}\n".format(time, level_str, self.prefix,
Expand Down
24 changes: 24 additions & 0 deletions tests/common/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,30 @@ def test_logger_should_log_in_utc(self):
# If the time difference is > 5secs, there's a high probability that the time_in_file is in different TZ
self.assertTrue((time_in_file-before_write_utc) <= timedelta(seconds=5))

@patch("azurelinuxagent.common.logger.datetime")
def test_logger_should_log_micro_seconds(self, mock_dt):
# datetime.isoformat() skips ms if ms=0, this test ensures that ms is always set

file_name = "test.log"
file_path = os.path.join(self.tmp_dir, file_name)
test_logger = logger.Logger()
test_logger.add_appender(logger.AppenderType.FILE, logger.LogLevel.INFO, path=file_path)

ts_with_no_ms = datetime.utcnow().replace(microsecond=0)
mock_dt.utcnow = MagicMock(return_value=ts_with_no_ms)

test_logger.info("The time should contain milli-seconds")

with open(file_path, "r") as log_file:
log = log_file.read()
try:
time_in_file = datetime.strptime(log.split(logger.LogLevel.STRINGS[logger.LogLevel.INFO])[0].strip()
, u'%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
self.fail("Ensure timestamp follows ISO-8601 format and has micro seconds in it")

self.assertEqual(ts_with_no_ms, time_in_file, "Timestamps dont match")

def test_telemetry_logger(self):
mock = MagicMock()
appender = logger.TelemetryAppender(logger.LogLevel.WARNING, mock)
Expand Down

0 comments on commit 435dd44

Please sign in to comment.