0

I am trying to set up logging to JSON file and I need nanoseconds to be logged. However when I try the next structure

<JsonLayout compact="true" properties="true" eventEol="true" >
    <KeyValuePair key="timestamp" value="$${date:HH:mm:ss.nnnnnnnnn}" />
</JsonLayout>

I get the error:

ERROR Invalid date format: [HH:mm:ss.nnnnnnnnn], using default java.lang.IllegalArgumentException: Illegal pattern character 'n'

I tried different patterns with nanoseconds with no success.

For .log file the next pattern works, however, it doesn't work for .json (or I apply it incorrectly).

<PatternLayout pattern="%d{DEFAULT_NANOS} />

Any ideas?

P.S. Log4j 2.11.0

Tatiana Goretskaya
  • 536
  • 10
  • 25
  • The json format should include an `Instant` element with epochSeconds and nanos (of that second) as attributes. Are you seeing that (if you don’t try to format the time stamp)? – Remko Popma Apr 16 '18 at 22:22
  • Seems you are trying to log using custom property logging format, try S instead of n `HH:mm:ss:SSSSSSSSS`, but if SimpleDateFOrmat is used in the background, it will fail. From the javadoc `If the number of pattern letters is 4 or more, IllegalArgumentException is thrown ` – LMC Apr 16 '18 at 22:38
  • @LuisMuñoz what javadoc? Note the formatting is done by a custom Log4j2 formatter. – Remko Popma Apr 17 '18 at 10:46
  • [This javadoc](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html). As far as I could see, [JsonLayout is part of the api](https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout), not a custom one. – LMC Apr 17 '18 at 14:09
  • @LuisMuñoz it fails with more than 3 "S" – Tatiana Goretskaya Apr 18 '18 at 17:23
  • @RemkoPopma yes, but I wanted to include more "human readable" form. – Tatiana Goretskaya Apr 18 '18 at 17:24
  • Ok. You can propose a change to Log4j2. Pull requests and patches always welcome! – Remko Popma Apr 18 '18 at 20:30

1 Answers1

1

I had this exact same error.

There are two classes which parse the Date Pattern, FixedDateFormat and FastDateFormat. The error comes from FastDateFormat, as it does not support the 'n' format in the date field. The reason FastDateFormat is being invoked is because during construction of the display Format, FixedDateFormat does not recognize the date pattern as valid.

I studied the specification in this question to find the reason FixedDateFormat does not parse the date pattern as intended, but I could not find the reason. If I find the reason, I will post an update to this answer.

In my case, I had the pattern 'dd MMM YYYY HH:mm:ss,nnnnnnnnn' instead of the valid pattern 'dd MMM yyyy HH:mm:ss,nnnnnnnnn' (note the incorrect capitalization of 'y').

codeDr
  • 1,535
  • 17
  • 20