6
votes

I am trying to use properties in a log4j2.yaml. The equivalent XML is this.

<Configuration>
<Properties>
    <Property name="log-path">logs</Property>
    <Property name="archive">${log-path}/archive</Property>
</Properties>
<Appenders>
. . .

I tried this.

Configutation:
  name: Default
  properties:
    property:
      name: log-path
      value: "logs"
      name: archive
      value: ${log-path}/archive
  Appenders:

But the properties are not getting picked. For example, the following code creates a ${log-path} folder to store a log file instead of the desired logs folder.

fileName: ${log-path}/rollingfile.log

What am I doing wrong?

1

1 Answers

10
votes

If you look at the log4j2.json file you can see that the property key has to have a value that is is list of (again) key-value pairs. Translated to YAML this looks like the beginning of this file:

configuration:
  name: Default
  properties:
    property:
    - name: log-path
      value: logs
    - name: archive
      value: ${log-path}/archive
  appenders:
    Console:
      PatternLayout:
        pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
      name: Console-Appender
      target: SYSTEM_OUT
    File:
      PatternLayout:
        pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
      fileName: ${log-path}/logfile.log
      name: File-Appender
    RollingFile:
      DefaultRolloverStrategy:
        max: '30'
      PatternLayout:
        pattern: '[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n'
      Policies:
        SizeBasedTriggeringPolicy:
          size: 1 KB
      fileName: ${log-path}/rollingfile.log
      filePattern: ${archive}/rollingfile.log.%d{yyyy-MM-dd-hh-mm}.gz
      name: RollingFile-Appender
  loggers:
    logger:
      additivity: 'false'
      appender-ref:
      - level: info
        ref: Console-Appender
      - level: error
        ref: File-Appender
      - level: debug
        ref: RollingFile-Appender
      level: debug
      name: guru.springframework.blog.log4j2json
    root:
      appender-ref:
        ref: Console-Appender
      level: debug

(the above was converted using yaml from-json log4j2.json, with the command being installed from ruamel.yaml.cmd

There is of course guarantee that this works, as there are multiple ways to convert an XML hierarchy to YAML. But it is not very likely that parsing of YAML and JSON differ.

The expansion of ${} has to be done after loading the YAML file, by walking the data-structure, and it is unlikely that this is done by matching the original mapping keys in a case-insensitive way.