Java - Logback to display testcase name - java

I am using Logback in my Selenium Webdriver project and I've reached a bit of a roadblock. I've search online but not been able to find the answer.
I am trying to find a way which allows me to get the testcase name (testGoogleWebsite) once inside the setup() method. So instead of just printing "Starting test" it prints out "Starting test - testGoogleWebsite"
I know I can do LOG.debug("testGoogleWebsite"); on the first line of each test, but wanted to know if there's a better way.
My Test:
#Test
public void testGoogleWebsite() {
openGoogleWebsite();
searchForStackOverflow();
clickOnStackOverflowLink();
}
#BeforeTest
public void setup() throws FileNotFoundException {
LOG.debug("Starting test - ");
driver = new ChromeDriver();
}
#AfterTest
public void tearDown(){
LOG.debug("End of test");
}
My logback file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="DEV_HOME" value="target/Logs" />
<appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/debug.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<logger name="com.test" level="debug" additivity="false">
<appender-ref ref="FILE-AUDIT" />
</logger>
<root level="debug">
<appender-ref ref="FILE-AUDIT" />
</root>
</configuration>

I think you are talking about logging your testacse name (as testGoogleWebsite is a testcase name I see). To do this you can put your LOG.debug("Starting test - "); in beforeMethod.
Code snippet
#BeforeMethod
public void beforeMethod(Method method) {
LOG.debug("Starting test - " + method.getName(););
}
This will log your each and every testcase name as you wanted.

Related

Logback NOT writing in log.txt

Problem Statement: Logback is printing in console properly but not in log.txt file. There are many solutions given in other pages but apparently none worked. Could someone help me in this regard?
Java:-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Log {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger("Example App");
logger.info("'sup? I'm your info logger");
logger.debug("hey HEY hey! I'm your debug logger");
}
}
Config:- logback-fileAppender.xml
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${project.basedir}/Log.txt</file>
<append>true</append>
<!-- set immediateFlush to false for much higher logging throughput -->
<immediateFlush>true</immediateFlush>
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
Expected:- The logs should be printed in log.txt
Actual:- The logs is not printed in log.txt
Note: I am using my customized directory structure in maven not the default provided by maven "src/main/resources".

How to enable log-back log stack trace og uncaught exceptions

I'm very new to log back and want to try using it in my app. I tried to configure it as follows:
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/file/log.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>/rotated/log.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- keep 30 days' worth of history capped at 3GB total size -->
<maxHistory>30</maxHistory>
<totalSizeCap>16GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
When I write a simple application I have a problem that stacktraces of uncaught exceptions are not get logged:
public static void main(String[] args){
logger.info("Test")
logger.error("TEST!")
throw new IllegalArgumentException("Exception")
}
And what I have in the log file is:
16:57:05.905 [main] INFO com.App - Test
16:57:05.907 [main] ERROR com.App - TEST!
How to configure logging stacktraces of uncaught exceptions?
I don't think that you can log uncaught exceptions outside your main() method at all. But what you CAN do is to use a "catch all" block in your main method:
public static void main(String[] args){
try
{
logger.info("Test");
logger.error("TEST!");
someMethodThatPropablyThrowsAnException();
throw new IllegalArgumentException("Exception");
}
catch (Exception exception)
{
logger.error(exception);
}
}
This should log any exception thrown in your code that was not handled yet.

Logback Dynamic Files using Two Properties

my problem is : My application maintains three buildings, and each building has a different process.
So, using logback, I want to create a log which has a specification :
each building will have a specific folder, and inside that specific folder of each building, there will be many log files, with each log file indicates a process.
My logback.xml right now is :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="logAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>processName</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<sift>
<appender name="FILE-${processName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/${distributor}/${processName}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern>
</layout>
<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>logs/${distributor}/${processName}.%i.log</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
<!-- <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>5KB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> -->
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>10MB</maxFileSize>
</triggeringPolicy>
</appender>
</sift>
</appender>
<logger name="processLog" level="debug" additivity="false">
<appender-ref ref="logAppender" />
<appender-ref ref="stdout" />
</logger>
<root level="debug">
<appender-ref ref="stdout" />
<appender-ref ref="logAppender" />
</root>
</configuration>
And my java servlet code is :
public class DistributorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger processLog = LoggerFactory.getLogger("processLog");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String office = req.getParameter("office");
MDC.put("distributor", office);
String process = req.getParameter("process");
MDC.put("process", process);
processLog.debug("Processing");
}
}
However, a log file is not generated.
Can anyone help me?
Thank you very much
1. Make the below change
private static Logger processLog = LoggerFactory.getLogger("processLog");
to
private static Logger processLog = LoggerFactory.getLogger(DistributorServlet .class);
2. Add additional discriminator for distributor
From the logback.xml it appears that only one discriminator has been added. Did you try adding another one for distributor
3. Do not forget
To add MDC.remove("keyName"); after its usage.
4. In case if you observe issue with multiple MDC keys
I faced an issue with the MDC.put in trying to add multiple keys into it. (I wondered why no putAll has been defined)
Although the underlying implementation is that of a HashMap<Key k, Value v> that should allow adding multiple keys, I was only able to see that the last key you put into MDC would be applied to logback.xml
While for the other keys I observed _IS_UNDEFINED value that gets appended instead.
Of course then again you can refer to the other various links and although this may not be a best idea, here is what I have done in my Java code,
System.setProperty("distributor", req.getParameter("office"));
System.setProperty("process", req.getParameter("process"));
Modify the logback.xml by removing discriminator. Well, alternatively you can remove one of the above properties and have the MDC.put for that property.
However please do refer to the links System.setProperty is safe in java?
Alternatively I suggest https://stackoverflow.com/a/32615172/3838328

Make logback pattern part optional?

Is it possible to make parts of logbacks pattern layout depending on an attribute?
e.g. show bdid (...) just in the case when %X{bdid} exists?
This appender
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>bdid\(%X{bdid}\) - %d{HH:mm:ss.SSS} %msg%n</pattern>
</encoder>
</appender>
prints
bdid(0b5d3877-f3dd-4189-8b1b-489c8b617f2a) 18:22:25.206 if bdid exists, but prints
bdid() 18:22:20.928 if it doesn't.
How do I omit the empty bdid() in my log?
You can use the replace function, details are in the docs here. A working example is the following:
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%replace(bdid\(%X{bdid}\)){'bdid\(\)', ''} - %d{HH:mm:ss.SSS} %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Test Function
public class PatternTest
{
#Test
public void test()
{
Logger logger = LoggerFactory.getLogger(PatternTest.class);
MDC.put("bdid", "hola");
logger.info("Check enclosed.");
MDC.remove("bdid");
logger.info("Check enclosed.");
}
}
Test output
bdid(hola) - 18:40:40.233 Check enclosed.
- 18:40:40.234 Check enclosed.

Strange behavior of Logback - empty files

I'm refurbishing old system that used logback, some simple stuff ( 3 appenders, 2 loggers ). Now in next version of system ( or re-implementation as the previous version was stolen with notebook and backup, only config file and binaries were already on robot ), I use the same config file, but all log files stays empty.
Strange thing is that it actually creates correct files and folders by the given patterns, so it definitely do something with the config file. Besides that, loggers and appenders aren't working at all.
I also tried to use various other configuration files I found on examples - not even one worked, so I'm suspicious that there is some collision between used libraries and logback. I tried to google it, but found nothing relevant or working.
Have anyone of you came around ( or hopefully through ) such a problem? Or please point at the wrong line...
Thx in advance...
Kamil
Next code shows initialization:
public static final String LOGGER_CONFIG_FILE = "hacs.logger.conf";
public static final String LOGGER_CONFIG_FILE_DEFAULT = "./conf/logconf.xml";
public static void main( String[] args ) {
File configurationFile = new File(HACSProperties.instance().getProperty(LOGGER_CONFIG_FILE, LOGGER_CONFIG_FILE_DEFAULT));
if( configurationFile.exists() ){
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset(); // When this is commented, logback works in some default configuration
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure( LOGGER_CONFIG_FILE_DEFAULT );
System.out.println("Logger successfully configured..");
Logger log = LoggerFactory.getLogger("analytics");
log.info( "Please appear in file" );
} catch (JoranException je) {
System.out.println("Error - failed to configure logger. Please check configuration.");
je.printStackTrace();
System.exit( 1 );
}
} else {
System.out.println("Error - failed to configure logger - configuration file does not exist. Please check configuration.");
System.exit( 2 );
}
}
Config file itself:
<configuration>
<timestamp key="bySecond" datePattern="dd.MM.yyyy'_T'HH.mm.ss" timeReference="contextBirth" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>./logs/HACS_LAST_RUN.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="FILE_PER_MINUTE" class="ch.qos.logback.core.FileAppender">
<file>./logs/PER_MINUTE/HACS-RUN-${bySecond}.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} %level [%file:%line] %msg%n</Pattern>
</layout>
</appender>
<logger name="org.hibernate" additivity="false">
<level value="warn" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</logger>
<logger name="FILE_ONLY" additivity="false">
<level value="INFO" />
<appender-ref ref="FILE_PER_MINUTE" />
<appender-ref ref="FILE" />
</logger>
<root>
<level value="INFO" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</root>
</configuration>
List of libraries:
antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.jar
bcprov-jdk15-1.43.jar
cglib-2.2.jar
chronicle.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
commons-pool-1.5.2.jar
cxf-2.3.0.jar
cxf-manifest.jar
cxf-xjc-boolean-2.3.0.jar
cxf-xjc-bug671-2.3.0.jar
cxf-xjc-dv-2.3.0.jar
cxf-xjc-ts-2.3.0.jar
dom4j-1.6.1.jar
FastInfoset-1.2.8.jar
felix.jar
geronimo-activation_1.1_spec-1.1.jar
geronimo-annotation_1.0_spec-1.1.1.jar
geronimo-javamail_1.4_spec-1.7.1.jar
geronimo-jaxws_2.2_spec-1.0.jar
geronimo-jms_1.1_spec-1.1.1.jar
geronimo-servlet_3.0_spec-1.0.jar
geronimo-stax-api_1.0_spec-1.0.1.jar
geronimo-ws-metadata_2.0_spec-1.1.3.jar
groovy-all-1.8.5.jar
h2-1.3.154.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jaxb-api-2.2.1.jar
jaxb-impl-2.2.1.1.jar
jaxb-xjc-2.2.1.1.jar
jettison-1.2.jar
jetty-continuation-7.1.6.v20100715.jar
jetty-http-7.1.6.v20100715.jar
jetty-io-7.1.6.v20100715.jar
jetty-server-7.1.6.v20100715.jar
jetty-util-7.1.6.v20100715.jar
jmdns.jar
jra-1.0-alpha-4.jar
js-1.7R1.jar
jsr311-api-1.1.1.jar
jta-1.1.jar
logback-access-1.0.1.jar
logback-classic-1.0.1.jar
logback-core-1.0.1.jar
neethi-2.0.4.jar
oro-2.0.8.jar
saaj-api-1.3.jar
saaj-impl-1.3.2.jar
serializer-2.7.1.jar
slf4j-api-1.6.4.jar
spring-aop-3.0.4.RELEASE.jar
spring-asm-3.0.4.RELEASE.jar
spring-beans-3.0.4.RELEASE.jar
spring-context-3.0.4.RELEASE.jar
spring-core-3.0.4.RELEASE.jar
spring-expression-3.0.4.RELEASE.jar
spring-jms-3.0.4.RELEASE.jar
spring-tx-3.0.4.RELEASE.jar
spring-web-3.0.4.RELEASE.jar
stax2-api-3.0.2.jar
velocity-1.6.4.jar
waiter-dns.jar
woodstox-core-asl-4.0.8.jar
wsdl4j-1.6.2.jar
wss4j-1.5.9.jar
xalan-2.7.1.jar
xml-resolver-1.2.jar
xmlbeans-2.4.0.jar
XmlSchema-1.4.7.jar
xmlsec-1.4.3.jar

Categories

Resources