cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Learn all about PTC Community Badges. Engage with PTC and see how many you can earn! X

Print different statements in different logger

AK_10341824
6-Contributor

Print different statements in different logger

Initially posted in this topic

 

Hi @HelesicPetr , I want to print different statements in different logger. Can you please help me here?
For example, I want different loggers purpose wise. Please refer to the below section.

private static final Logger LOGGER = LogManager.getLogger(LoggerExample.class );

private static final Logger LOGGER_PRE = LogManager.getLogger("LoggerExample_Pre");

private static final Logger LOGGER_SUMMARY = LogManager.getLogger("LoggerExample_Summary");

private static final Logger LOGGER_POST = LogManager.getLogger("LoggerExample_Post");

private static final Logger LOGGER_ERROR = LogManager.getLogger("LoggerExample_Error");

 

ACCEPTED SOLUTION

Accepted Solutions

Hi @AK_10341824 

But in your config there is not definition for the Logger> LoggerExample_Pre 

 

There is logger ext.test.LoggerExample

 

the LoggerExample_Pre definition is just appender that appends the ext.test.LoggerExample logger.

 

you need to define another logger with that name.

 

logger.LoggerExample_Pre.name=ext.test.LoggerExample_Pre 
logger.LoggerExample_Pre.level=DEBUG 

 

and so on...

 

PetrH

View solution in original post

7 REPLIES 7
avillanueva
22-Sapphire II
(To:AK_10341824)

Here is what I do in my code:

Imports look like this for 

import org.apache.logging.log4j.Logger; //updated for Log4J 2.x
import wt.log4j.LogR;

Note my update for Log4J 2.x as @HelesicPetr mentioned. In the code block I call out my logger which is typically the class name.

private static Logger log=null;

    static
    {
        try
        {
            log = LogR.getLogger(MyCustomClass.class.getName());
        }
        catch(Exception e)
        {
        }
    }

 In your example, I would just repeat that call for each one. Seems excessive but your call.

Hi @avillanueva , Can you please help me to configure these different log files for a single java code in log4jMethodserver.properties?

AK_10341824_0-1700466273876.png

I entered for Pre logger only. But it was not working properly.

Hi @AK_10341824 

Please describe what is not working.

PetrH

@HelesicPetr ,

Please refer to the below sample code:

package ext.test;
 
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.util.WTException;
 
public class LoggerExample implements RemoteAccess {
private static final Logger LOGGER = LogManager.getLogger(LoggerExample.class);
private static final Logger LOGGER_PRE = LogManager.getLogger("LoggerExample_Pre");
    private static final Logger LOGGER_SUMMARY = LogManager.getLogger("LoggerExample_Summary");
    private static final Logger LOGGER_POST = LogManager.getLogger("LoggerExample_Post");
    private static final Logger LOGGER_ERROR = LogManager.getLogger("LoggerExample_Error");
    
    private static final int USERNAME_INDEX = 0;
    private static final int USERNAME_VALUE_INDEX = 1;
    private static final int PASSWORD_VALUE_INDEX = 3;
    
    private static int processedPartMasterCount = 0;
    private static int successfulPartMasterCount = 0;
    private static int failedPartMasterCount = 0;
    private static RemoteMethodServer rms;
 
public static void main(String[] args) throws RemoteException, InvocationTargetException {
LOGGER.debug("ENTER : LoggerExample.class.main(String[])");
        try {
            long startTime = System.currentTimeMillis();
            LOGGER.debug("LoggerExample.class StartTime : " + startTime);
            rms = getConnection(args);
            if (rms != null) {
            rms.invoke("doSomething", LoggerExample.class.getName(), null, new Class[] {}, new Object[] {});
                long endTime = System.currentTimeMillis();
                LOGGER.debug("LoggerExample.class EndTime : " + endTime);
                long totalTimeTaken = endTime - startTime;
                rms.invoke("printSummaryLogs", LoggerExample.class.getName(), null, new Class[] { Long.class }, new Object[] {totalTimeTaken});
                processedPartMasterCount = 0;
                successfulPartMasterCount = 0;
                failedPartMasterCount = 0;
            }
        } catch (Exception e) {
            LOGGER.error("Exception occured while executing the utility.", e);
        }
        LOGGER.debug("EXIT : LoggerExample.main(String[])");
}
 
    public static RemoteMethodServer getConnection(String[] args) throws WTException {
        LOGGER.debug("ENTER : LoggerExample.getConnection(String[])");
        String username = null;
        String password = null;
        if ("-u".equals(args[USERNAME_INDEX])) {
            username = args[USERNAME_VALUE_INDEX];
            password = args[PASSWORD_VALUE_INDEX];
        }
        RemoteMethodServer remoteMethodServer = RemoteMethodServer.getDefault();
        if (username != null && !"".equals(username)) {
            remoteMethodServer.setUserName(username);
            if (password != null) {
                remoteMethodServer.setPassword(password);
            }
        }
        LOGGER.debug("EXIT : LoggerExample.getConnection(String[])");
        return remoteMethodServer;
    }
    
    public static void doSomething() {
    LOGGER.debug("Inside doSomething() method...");
    LOGGER_PRE.debug("Inside doSomething() method...");
    LOGGER_SUMMARY.debug("Inside doSomething() method...");
    LOGGER_POST.debug("Inside doSomething() method...");
    LOGGER_ERROR.debug("Inside doSomething() method...");
    }
    
    public static void printSummaryLogs(Long totalTimeTaken) {
        LOGGER.debug("ENTER : LoggerExample.printSummaryLogs(Long)");
        long totalTimeInMilis = totalTimeTaken.longValue();
        LOGGER.debug("Total time taken in miliSeconds : " + totalTimeInMilis);
 
        LOGGER_PRE.debug("Only for Pre log Inside printSummaryLogs() method...");
    LOGGER_SUMMARY.debug("Inside printSummaryLogs() method...");
    LOGGER_POST.debug("Inside printSummaryLogs() method...");
    LOGGER_ERROR.debug("Inside printSummaryLogs() method...");
        
        LOGGER_PRE.info("Logger Example :: Summary");
        LOGGER.info("=======================================");
        LOGGER.info("Number of traceable Part Master(s) : " + processedPartMasterCount);
        LOGGER.info("Number of succssfully updated Part Master(s) : " + successfulPartMasterCount);
        LOGGER.info("Number of Part Master(s) : " + failedPartMasterCount);
        LOGGER.debug("EXIT : LoggerExample.printSummaryLogs(Long)");
    }
}

=================================================================================================
Log4jMethodServer.properties entries

logger.LoggerExample.name=ext.test.LoggerExample
logger.LoggerExample.level=DEBUG
logger.LoggerExample.appenderRef.LoggerExample_Pre.ref=LoggerExample_Pre

# Pre-logger
appender.LoggerExample_Pre.type = RollingFile
appender.LoggerExample_Pre.name = LoggerExample_Pre
appender.LoggerExample_Pre.createOnDemand = true
appender.LoggerExample_Pre.fileName = ${sys:wt.logs.dir}/LoggerExampleUtility/LoggerExample_Pre-${sys:wt.manager.serviceName}-${sys:wt.jvm.startTime.formatted.short}-${sys:wt.jvm.id}-log4j.log
appender.LoggerExample_Pre.filePattern = ${sys:wt.logs.dir}/LoggerExampleUtility/LoggerExample_Pre-${sys:wt.manager.serviceName}-${sys:wt.jvm.startTime.formatted.short}-${sys:wt.jvm.id}-log4j.log.%d{yyyy-MM-dd}_%i
appender.LoggerExample_Pre.layout.type = PatternLayout
appender.LoggerExample_Pre.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS}{${timeZone}} [%-5p]-[%t]-%c[%M] - %m%ex%n
appender.LoggerExample_Pre.policies.type = Policies
appender.LoggerExample_Pre.policies.midnight.type = SizeBasedMidnightTriggeringPolicy
appender.LoggerExample_Pre.policies.midnight.size=9MB
appender.LoggerExample_Pre.strategy.type = DefaultRolloverStrategy
appender.LoggerExample_Pre.strategy.max =2147483647

But I am getting output logs only for LOGGER.debug, LOGGER.info all these.
I need to get output in LOGGER_PRE.debug, LOGGER_POST.debug too.
Can you please help me here?

Hi @AK_10341824 

But in your config there is not definition for the Logger> LoggerExample_Pre 

 

There is logger ext.test.LoggerExample

 

the LoggerExample_Pre definition is just appender that appends the ext.test.LoggerExample logger.

 

you need to define another logger with that name.

 

logger.LoggerExample_Pre.name=ext.test.LoggerExample_Pre 
logger.LoggerExample_Pre.level=DEBUG 

 

and so on...

 

PetrH

Hi @HelesicPetr , thanks a lot for your help. It works.😃

Hi @AK_10341824 

The original post talk about configuration in the log4jMethodServer.properties

If you want to use your own logger in your code, use the LogR.getLogger

With this method, you can use any logger name. Not just class name. 

for example I use logger for all classes in specific functionality.  

LogR.getLogger("cz.aveng.WVSPublish");

the WVSPublish is not existing class

LogR.getLogger("cz.aveng.WVSPublish");

your logger could be 

private static final Logger LOGGER_ERROR = LogR.getLogger("LoggerExample_Error");

 

PetrH

Announcements

Top Tags