88import org .apache .log4j .spi .LocationInfo ;
99import org .apache .log4j .spi .LoggingEvent ;
1010import org .apache .log4j .spi .ThrowableInformation ;
11- import sun .util .logging .resources .logging ;
1211
1312import java .io .Serializable ;
1413import java .lang .reflect .Field ;
2019
2120public class JSONEventLayoutV0 extends Layout {
2221
22+ private boolean renderObjectFields = false ;
2323 private boolean locationInfo = false ;
2424
2525 private String tags ;
@@ -49,16 +49,19 @@ public static String dateFormat(long timestamp) {
4949 * in the log messages.
5050 */
5151 public JSONEventLayoutV0 () {
52- this (true );
52+ this (true , false );
5353 }
5454
5555 /**
5656 * Creates a layout that optionally inserts location information into log messages.
5757 *
5858 * @param locationInfo whether or not to include location information in the log messages.
59+ * @param renderObjectFields whether or not to render the fields of the message object into the json when an object is logged to log4j.
60+ * Rendering the fields is done using reflection and incurs a performance cost
5961 */
60- public JSONEventLayoutV0 (boolean locationInfo ) {
62+ public JSONEventLayoutV0 (boolean locationInfo , boolean renderObjectFields ) {
6163 this .locationInfo = locationInfo ;
64+ this .renderObjectFields = renderObjectFields ;
6265 }
6366
6467 public String format (LoggingEvent loggingEvent ) {
@@ -73,12 +76,15 @@ public String format(LoggingEvent loggingEvent) {
7376
7477 logstashEvent .put ("@source_host" , hostname );
7578 logstashEvent .put ("@message" , loggingEvent .getRenderedMessage ());
76- Object messageObj = loggingEvent .getMessage ();
77- if (messageObj instanceof Serializable && !(messageObj instanceof String )) {
78- addObjectFieldData (messageObj );
79- }
8079 logstashEvent .put ("@timestamp" , dateFormat (timestamp ));
8180
81+ if (renderObjectFields ) {
82+ Object messageObj = loggingEvent .getMessage ();
83+ if (messageObj instanceof Serializable && !(messageObj instanceof String )) {
84+ addObjectFieldData (messageObj );
85+ }
86+ }
87+
8288 if (loggingEvent .getThrowableInformation () != null ) {
8389 final ThrowableInformation throwableInformation = loggingEvent .getThrowableInformation ();
8490 if (throwableInformation .getThrowable ().getClass ().getCanonicalName () != null ) {
@@ -160,6 +166,15 @@ public void setLocationInfo(boolean locationInfo) {
160166 this .locationInfo = locationInfo ;
161167 }
162168
169+ /**
170+ * Set whether or not to render the fields of the message object into the json when an object is logged to log4j.
171+ * Rendering the fields is done using reflection and incurs a performance cost
172+ * @param renderObjectFields
173+ */
174+ public void setRenderObjectFields (boolean renderObjectFields ) {
175+ this .renderObjectFields = renderObjectFields ;
176+ }
177+
163178 public void activateOptions () {
164179 activeIgnoreThrowable = ignoreThrowable ;
165180 }
0 commit comments