sop
sop

Reputation: 3625

Printing the timestamp milliseconds in R does not work

I have an application that logs some info in R. I am using logging library for that. My problem is that the timestamp has no milliseconds, and I get not always the good order of the logs. In the logging file, R puts the logs in the right order, but I use logstash and es for having the history and for monitoring. Because the timestamp I got not the right order of the logs, so I would like to add milliseconds.

I have tried to use strptime and %OS(n), but it seems not to work. If I add the %OS, I get NA even for simple things:

strptime(Sys.time(), "%H:%M:%OS")

I have seen that there are more posts like this, but no answer, so I am posting it here, too.

I have to say that I use R 3.2.0 under Linux Ubuntu 14.04. How to solve it? How to have milliseconds in timestamp?


OK, after using strftime, I am getting the milliseconds, but it seems that they are always 0.

I have a log formater:

logFormatter <- function(record) {
  sprintf('Application(%s) %s [%s] [] %s - %s', format(as.hexmode(Sys.getpid()), width = 8), record$levelname, strftime(record$timestamp, "%Y-%m-%dT%H:%M:%OS3"), record$logger, record$msg)
}

I have added the logger:

addHandler(writeToFile, logger = "MyLogger", file = "/var/log/Application/logs.log", level = 'INFO', formatter = logFormatter)

and I log like this:

loginfo("some info X", logger = MyLogger)

but the output seems to be always at the beginning of the second:

Application(000018f3) INFO [2015-09-21T11:45:56.000] [] some info 1
Application(000018f3) INFO [2015-09-21T11:45:58.000] [] some info 2
Application(000018f3) INFO [2015-09-21T11:45:58.000] [] some info 3
Application(000018f3) INFO [2015-09-21T11:45:58.000] [] some info 4
Application(000018f3) INFO [2015-09-21T11:45:59.000] [] some info 5

Upvotes: 1

Views: 252

Answers (2)

RHertel
RHertel

Reputation: 23788

To obtain millisecond information it is usually helpful to set

options(digits.secs = 3)

This will give, for instance

> strptime(Sys.time(), format =  "%Y-%m-%d %H:%M:%OS")
#[1] "2015-09-21 11:52:09.787 CEST"

Maybe this helps in your case.

Upvotes: 1

Nikos
Nikos

Reputation: 3297

I use the strftime instead of strptime, and there is an easy way to show milliseconds as follows:

strftime(Sys.time(), format="%Y-%m-%d %H:%M:%OS6")

which will output

[1] "2015-09-21 10:32:58.669559"

Is this helpful?

Upvotes: 3

Related Questions