com.ryo.log4j2.context.core.AbstractJacksonLayout.java Source code

Java tutorial

Introduction

Here is the source code for com.ryo.log4j2.context.core.AbstractJacksonLayout.java

Source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache license, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the license for the specific language governing permissions and
 * limitations under the license.
 */
package com.ryo.log4j2.context.core;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.ryo.log4j2.context.bean.MyLog4jLogEvent;
import com.ryo.log4j2.context.util.AppContextUtil;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.impl.MutableLogEvent;
import org.apache.logging.log4j.core.layout.AbstractStringLayout;
import org.apache.logging.log4j.core.util.StringBuilderWriter;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;

abstract class AbstractJacksonLayout extends AbstractStringLayout {

    protected static final String DEFAULT_EOL = "\r\n";
    protected static final String COMPACT_EOL = Strings.EMPTY;

    protected final String eol;
    protected final ObjectWriter objectWriter;
    protected final boolean compact;
    protected final boolean complete;

    protected AbstractJacksonLayout(final Configuration config, final ObjectWriter objectWriter,
            final Charset charset, final boolean compact, final boolean complete, final boolean eventEol,
            final Serializer headerSerializer, final Serializer footerSerializer) {
        super(config, charset, headerSerializer, footerSerializer);
        this.objectWriter = objectWriter;
        this.compact = compact;
        this.complete = complete;
        this.eol = compact && !eventEol ? COMPACT_EOL : DEFAULT_EOL;
    }

    /**
     * Formats a {@link LogEvent}.
     *
     * @param event The LogEvent.
     * @return The XML representation of the LogEvent.
     */
    @Override
    public String toSerializable(final LogEvent event) {
        final StringBuilderWriter writer = new StringBuilderWriter();
        try {
            toSerializable(event, writer);
            return writer.toString();
        } catch (final IOException e) {
            // Should this be an ISE or IAE?
            LOGGER.error(e);
            return Strings.EMPTY;
        }
    }

    private static LogEvent convertMutableToLog4jEvent(final LogEvent event) {
        // TODO Jackson-based layouts have certain filters set up for Log4jLogEvent.
        // TODO Need to set up the same filters for MutableLogEvent but don't know how...
        // This is a workaround.
        boolean isMutableLogEvent = event instanceof MutableLogEvent;
        String eventJson = JSON.toJSONString(event);
        LogEvent result = ((MutableLogEvent) event).createMemento();
        String memnTo = JSON.toJSONString(result);

        return event instanceof MutableLogEvent ? ((MutableLogEvent) event).createMemento() : event;
    }

    /**
     *  MyLog4jLogEvent
     * 1)  traceId
     * @return
     */
    private static MyLog4jLogEvent buildMyLog4jLogEvent(final LogEvent event) {
        MyLog4jLogEvent myLog4jLogEvent = new MyLog4jLogEvent();
        LogEvent logEvent = convertMutableToLog4jEvent(event);
        BeanUtils.copyProperties(logEvent, myLog4jLogEvent);

        myLog4jLogEvent.setLoggerName(logEvent.getLoggerName());
        myLog4jLogEvent.setMessage(logEvent.getMessage());
        myLog4jLogEvent.setEndOfBatch(logEvent.isEndOfBatch());
        myLog4jLogEvent.setLoggerFqcn(logEvent.getLoggerFqcn());

        myLog4jLogEvent.setTraceId("2017-2-15 18:19:23 TRACE ID");
        myLog4jLogEvent.setLogId(AppContextUtil.getCurrentInvokeId());

        return myLog4jLogEvent;
    }

    /**
     * {
     "timeMillis" : 1487154151864,
     "thread" : "main",
     "level" : "INFO",
     "loggerName" : "com.ryo.log4j2.context.MyJsonLayoutTest",  **
     "message" : "hello json",  **
     "endOfBatch" : false,  **
     "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",  **
     "threadId" : 1,
     "threadPriority" : 5
     }
        
        
     My:
     {
     "timeMillis" : 1487154192990,
     "thread" : "main",
     "level" : "OFF",
     "endOfBatch" : false,
     "traceId" : "2017-2-15 18:19:23 TRACE ID",
     "threadId" : 1,
     "threadPriority" : 5
     }
     * @param event
     * @param writer
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     */
    public void toSerializable(final LogEvent event, final Writer writer)
            throws JsonGenerationException, JsonMappingException, IOException {
        MyLog4jLogEvent myLog4jLogEvent = buildMyLog4jLogEvent(event);
        //        objectWriter.writeValue(writer, convertMutableToLog4jEvent(event));
        objectWriter.writeValue(writer, myLog4jLogEvent);
        writer.write(eol);
        markEvent();
    }

}