I have to convert a pattern layout written for log4j 1.2. to log4j2.
Following code snippet shows a part of it. I have searched a lot about this
but couldn't find a proper guide.
Can anyone please give me a brief guide about how to do this conversion ?

Any help is highly appreciated!

public class CustomPatternLayout extends PatternLayout {

public static final String DEFAULT_PATTERN = "[%T][%S]";
private static String customPattern = DEFAULT_PATTERN;

public CustomPatternLayout(String pattern) {
    super(pattern);}
public synchronized void setCustomPattern(String customPattern) {
    CustomPatternLayout.customPattern = customPattern;}

private static class customPatternParser extends PatternParser {

    protected void finalizeConverter(char c) {
        PatternConverter pc = null;
        switch (c) {
            case 'P':
                pc = new UserNamePatternConverter(formattingInfo,
extractPrecisionOption());
                break;
                .
                .
                .
            default:
                super.finalizeConverter(c);
        }
        if (pc != null) {
            currentLiteral.setLength(0);
            addConverter(pc);
        }
    }
private abstract static class CustomNamedPatternConverter extends
PatternConverter {

        private int precision;

        public CustomNamedPatternConverter(FormattingInfo
formattingInfo, int precision) {
            super(formattingInfo);
            this.precision = precision;
        }

        protected abstract String getFullyQualifiedName(LoggingEvent event);

        public String convert(LoggingEvent event) {
            String n = getFullyQualifiedName(event);
            if (n == null) {
                return "";
            }
            if (precision <= 0) {
                return n;
            } else {
                int len = n.length();
                int end = len - 1;
                for (int i = precision; i > 0; i--) {
                    end = n.lastIndexOf('.', end - 1);
                    if (end == -1) {
                        return n;
                    }
                }
                return n.substring(end + 1, len);
            }
        }
    }

    private static class MyPatternConverter extends
CustomNamedPatternConverter {

        public MyPatternConverter(FormattingInfo formattingInfo, int
precision) {
            super(formattingInfo, precision);
        }

        public String getFullyQualifiedName(LoggingEvent event) {
            int userId = //Get user Id
            if ( . . .) {
                return new CustomPatternLayout(customPattern).format(event);
            }
            return someOther;
        }
    }}}

Thanks in advance.

-- 
Chathura Priyankara,
Faculty of Information Technology,
University of Moratuwa.
Blog  : www.codeoncloud.blogspot.com

Reply via email to