简体   繁体   中英

Add JsonLayout to log4j2 json config

I'm trying to redirect an output of log in a JSON format, so, I have a Json configuration for log4j2. I know that I should use the JsonLayout, but I didn't find any way to put this on my configuration. That's my log4j2.json:

{
  "Configuration": {
    "status": "info",
    "Appenders": {
      "Console": {
        "name": "Console",
        "target": "SYSTEM_OUT",
        "PatternLayout": {
          "Pattern": "%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} [%t] %-5level [%logger{1.}] - %msg%n"
        }
      }
    },
    "Loggers": {
      "Root": {
        "level": "info",
        "AppenderRef": [
          {
            "ref": "Console"
          }
        ]
      }
    }
  }
}

Could you help me to add this to my configuration file?

Here's something working example, You simply need JSONLayout which is an impl of Layout for json event logging.

{
  "configuration": {
    "name": "log-enrichment",
    "appenders": {
      "RollingFile": {
        "name": "rollingFile",
        "fileName": "enrichment.log",
        "filePattern": "%d{MM-dd-yy-HH-mm-ss}-%i.log",
        "JSONLayout": {
          "complete": false,
          "compact": false,
          "eventEol": true
        },
        "SizeBasedTriggeringPolicy": {
          "size": "100 MB"
        },
        "DefaultRolloverStrategy": {
          "max": "5"
        }
      }
    },
    "loggers": {
      "root": {
        "level": "DEBUG",
        "appender-ref": {
          "ref": "rollingFile"
        }
      }
    }
  }
}

Here is an example. You should look at http://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout for the options you can use. Also, the configuration file does not have to be in JSON to use the JsonLayout. It alos could be XML, YAML, or a properties file.

{
  "Configuration": {
    "status": "info",
    "Appenders": {
      "Console": {
        "name": "Console",
        "target": "SYSTEM_OUT",
        "PatternLayout": {
          "Pattern": "%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} [%t] %-5level [%logger{1.}] - %msg%n"
        } 
      },
      "File" : {
        "name" : "file",
        "fileName" : "${env:logdir}/app.log",
        "JsonLayout" : {
          "complete" : "true"
        }
      }
    },
    "Loggers": {
      "Root": {
        "level": "info",
        "AppenderRef": [
          {
            "ref": "Console"
          },
          {
            "ref" : "File"
          }
        ]
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM