I have requirement to retain logs for last 50 days only (i only want logs for last 50 days only). in the log4j properties file i have maxbackup index set it to 1 for testing purposes. i am aware that log4j dailyrollingfileappender only rollover monthly yearly daily etc.
But my requirement is to roll over every day but only want for last 50 days, rest to be deleted.
So i have found CustomAppender which extends which extends daily rollingfileappender and my customappender looks as below. Basically we have added maxbackupindex to daily rollingfile appender.
Code:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.helpers.LogLog;
public class CustomAppender extends DailyRollingFileAppender {
private int maxBackupIndex;
public void setMaxBackupIndex(int maxBackupIndex) {
this.maxBackupIndex = maxBackupIndex;
}
#Override
public void rollOver() throws IOException {
super.rollOver();
File file = new File(fileName);
List<String> files = new ArrayList<>();
File[] dirFiles = new File(file.getAbsolutePath()).getParentFile().listFiles();
if (dirFiles != null && dirFiles.length > 0) {
Arrays.sort(dirFiles, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));
for (File allFile : dirFiles) {
if (allFile.getName().contains(fileName)) {
files.add(allFile.getAbsolutePath());
}
}
}
if (files.size() > maxBackupIndex+1) {
File deleteFile = new File(files.get(0));
LogLog.debug("delete result for"+deleteFile.getAbsolutePath()+" is "+deleteFile.delete());
files.remove(0);
}
}
}
my log4j properties looks below.
log4j.rootLogger=WARN,stdout
log4j.logger.X.Y.Z.A=DEBUG,Application
log4j.appender.Application=org.apache.log4j.CustomAppender
log4j.appender.Application.File=/h/i/logs/m/Application.log
log4j.appender.Application.MaxBackupIndex=1
log4j.appender.Application.layout=org.apache.log4j.PatternLayout
log4j.appender.Application.layout.ConversionPattern=%d{DATE} %-5p %m - %c [%t] [%r ms]%n%n
#set up the apache appender
log4j.logger.org.apache=ON
# Hibernate loggers and appender
#log4j.logger.org.hibernate=DEBUG,Hibernate
log4j.logger.org.hibernate=DEBUG,Hibernate
log4j.additivity.org.hibernate=false
log4j.logger.org.hibernate.SQL=DEBUG,Hibernate
log4j.additivity.org.hibernate.SQL=false
log4j.logger.org.hibernate.type=DEBUG,Hibernate
log4j.additivity.org.hibernate.type=false
log4j.appender.Hibernate=org.apache.log4j.CustomAppender
log4j.appender.Hibernate.File=/h/i/logs/m/Hibernate.log
log4j.appender.Hibernate.MaxBackupIndex=1
log4j.appender.Hibernate.layout=org.apache.log4j.PatternLayout
log4j.appender.Hibernate.layout.ConversionPattern=Hib: %d [%t] %-5p %c - %m%n%n
However, the previous files are not being deleted , even though maxbackupindex is set to 1.
any one can please help me out?
Related
I am creating trigger using here but it is not working at all and I am getting ConfigurationException: Trigger class 'org.apache.cassandra.triggers.AuditTrigger' doesn't exist.
Steps I followed to create trigger:
1: I have compiled my java file using
javac -cp /CassandraTriggerExample/lib/cassandra-all-3.6.jar
AuditTrigger.Java
2:Jar creation :
jar -cvf trigger-example.jar AuditTrigger.class
3: I checked content of my jar file:
"unzip -l trigger-example.jar"
4: Copied this jar file into:
cassandra_home/conf/triggers
5: Copied AuditTrigger.properties into:
cassandra_home/conf
6: Restarted cassandra server
7: ./nodetool -h localhost reloadtriggers
8: In system.log i can see the entry:
INFO [RMI TCP Connection(2)-127.0.0.1] 2018-07-22 22:15:25,827
CustomClassLoader.java:89 - Loading new jar
/Users/uname/cassandra/conf/triggers/trigger-example.jar
9: Now when i am creating my trigger using :
CREATE TRIGGER test1 ON test.test
USING 'org.apache.cassandra.triggers.AuditTrigger';
I am getting "ConfigurationException: Trigger class 'org.apache.cassandra.triggers.AuditTrigger' doesn't exist".
I think that the problem is that your jar isn't correctly packaged: if your class has name org.apache.cassandra.triggers.AuditTrigger, then it should be located under org/apache/cassandra/triggers/AuditTrigger.class inside jar file...
See this documentation for more details explanation how classes are found...
Did had a similar issue. Could be because you copied it but did not reload the trigger or created the trigger. Got it resolved by following the below checks and execution of command to re-load and create the trigger.
Check
Ensure that the class has name org.apache.cassandra.triggers.AuditTrigger and the same is located under org/apache/cassandra/triggers/AuditTrigger.class inside jar file.
CMD Command
Go to the bin folder of Cassandra installed folder to run the nodetool reloadtriggers command as below.
C:\Cassandra\apache-cassandra-3.11.6\bin>nodetool reloadtriggers
Execute the below statement at cqlsh prompt
CREATE TRIGGER test1 ON test.test USING 'org.apache.cassandra.triggers.AuditTrigger';
Your trigger should be now available!
In case if still the problem persists you can try to restart the server once to see if the same is available.
Find in the below code what I used to publish a message to Kafka consumer upon every insert to Cassandra DB as an example. You can modify the same for update. I used JDK 1.8.0_251, apache-cassandra-3.11.7, kafka_2.13-2.6.0 and Zookeeper-3.6.1.
/**
*
*/
package com.cass.kafka.insert.trigger;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.partitions.Partition;
import org.apache.cassandra.db.rows.Cell;
import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.db.rows.Unfiltered;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.triggers.ITrigger;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
/**
* #author Dinesh.Lomte
*
*/
public class InsertCassTriggerForKafkaPublish implements ITrigger {
private String topic;
private Producer<String, String> producer;
private ThreadPoolExecutor threadPoolExecutor;
/**
*
*/
public InsertCassTriggerForKafkaPublish() {
Thread.currentThread().setContextClassLoader(null);
topic = "test";
producer = new KafkaProducer<String, String>(getProps());
threadPoolExecutor = new ThreadPoolExecutor(4, 20, 30,
TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
}
/**
*
*/
#Override
public Collection<Mutation> augment(Partition partition) {
threadPoolExecutor.execute(() -> handleUpdate(partition));
return Collections.emptyList();
}
/**
*
* #param partition
*/
private void handleUpdate(Partition partition) {
if (!partition.partitionLevelDeletion().isLive()) {
return;
}
UnfilteredRowIterator it = partition.unfilteredIterator();
while (it.hasNext()) {
Unfiltered un = it.next();
Row row = (Row) un;
if (row.primaryKeyLivenessInfo().timestamp() != Long.MIN_VALUE) {
Iterator<Cell> cells = row.cells().iterator();
Iterator<ColumnDefinition> columns = row.columns().iterator();
while (cells.hasNext() && columns.hasNext()) {
ColumnDefinition columnDef = columns.next();
Cell cell = cells.next();
if ("payload_json".equals(columnDef.name.toString())) {
producer.send(new ProducerRecord<>(
topic, columnDef.type.getString(cell.value())));
break;
}
}
}
}
}
/**
*
* #return
*/
private Properties getProps() {
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
return properties;
}
}
i'm actually trying to run a keyword from imported test library written in java (RF 3.0.2 , Jython 2.7.1rc3 )
import org.apache.log4j.Logger;
public class Sample
{
private static final Logger logger = Utils.getLogger(Sample.class);
#RobotKeyword("Print Message")
#ArgumentNames({"message"})
public void printMessage(String message)
{
logger.info("I'm inside");
}
}
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Utils
{
public static final Logger logger = getLogger(Utils.class);
public static Logger getLogger(Class<?> clazz)
Logger logger = Logger.getLogger(className.getClass());
PropertyConfigurator.configure("/src/main/resources/log4j.properties");
return logger;
}
log4j.properties :
log4j.rootLogger=DEBUG, Stdout, file
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.Target=System.out
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%d %-5p [%t] %F:%L %m%n
log4j.appender.Stdout.ImmediateFlush=true
log4j.appender.Stdout.follow=true
With this setup i'm able to see log after test execution in robot framework test report but it would be very helpful if i can see logs during test execution as if i was calling log to console keyword.
is There a way to do this ?
You can use listener interface http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#listener-interface to get real time execution information. In docs there is a sample script.
This is used in RED Robot Editor to get execution status,debug information etc. - source can be found:
TestRunnerAgent.py
This is my XML which I want to unmarshal (I do not have XSD for it). And I have to unmarshal it to get an array of names and Id's. So, names are getting generated just fine, but the issue is with the Id's. The Id's are set to null. Can anyone please help me identify the issue?
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" expressionLanguage="http://www.w3.org/1999/XPath" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" typeLanguage="http://www.w3.org/2001/XMLSchema">
<bpmn:collaboration id="Collaboration_0b6zt1k" isClosed="false">
<bpmn:participant id="Participant_113vq9r" processRef="CallActivity_00qe833" />
</bpmn:collaboration>
<bpmn:process id="CallActivity_00qe833" isClosed="false" isExecutable="true" name="Some Text" processType="None">
<bpmn:serviceTask activiti:class="Assign PC" completionQuantity="1" id="ServiceTask_0ip6tj7" implementation="##WebService" isForCompensation="false" name="Some Text 1" startQuantity="1">
<bpmn:extensionElements>
<activiti:properties>
<activiti:property name="specKey" value="ServiceTask_0ip6tj7" />
</activiti:properties>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_0sa9y9o</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_1bd3qmp</bpmn:outgoing>
</bpmn:serviceTask>
<bpmn:serviceTask activiti:class="generateURL" completionQuantity="1" id="ServiceTask_11t11da" implementation="##WebService" isForCompensation="false" name="Some Text 2" startQuantity="1">
<bpmn:extensionElements>
<activiti:properties>
<activiti:property name="specKey" value="ServiceTask_11t11da" />
</activiti:properties>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_1bd3qmp</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_0cynzzs</bpmn:outgoing>
</bpmn:serviceTask>
<bpmn:serviceTask activiti:class="generateURL" completionQuantity="1" id="ServiceTask_11t11da" implementation="##WebService" isForCompensation="false" name="Some Text 3" startQuantity="1">
<bpmn:extensionElements>
<activiti:properties>
<activiti:property name="specKey" value="ServiceTask_11t11da" />
</activiti:properties>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_1bd3qmp</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_0cynzzs</bpmn:outgoing>
</bpmn:serviceTask>
</bpmn:process>
</bpmn:definitions>
This is my JAXB annotated class:
package XMLToObject;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class definitions {
#XmlPath("bpmn:process/bpmn:serviceTask/#name")
#XmlAttribute
List<String> name;
#XmlPath("bpmn:process/bpmn:serviceTask/#id")
#XmlAttribute
List<String> id;
#XmlAttribute
String typeLanguage;
public List<String> getname() {
return name;
}
public List<String> getid() {
return id;
}
public String gettypeLanguage() {
return typeLanguage;
}
}
This is my Java Class:
package XMLToObject;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Gauravb
*/
import java.io.File;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class XMLToObject {
public static void main(String[] args) {
try {
File file = new File("employee.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(definitions.class);
System.out.println("JAXB....."+jaxbContext.toString());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
definitions p = (definitions) jaxbUnmarshaller.unmarshal(file);
System.out.println("Task Name:"+p.getname());
System.out.println("Svc ID:"+p.getid());
System.out.println("Type Language:"+p.gettypeLanguage());
} catch (JAXBException e) {e.printStackTrace(); }
}
}
Now, this is the output I am getting:
run:
JAXB.....org.eclipse.persistence.jaxb.JAXBContext#18eed359
Task Name:[Some Text 1, Some Text 2, Some Text 3]
Svc ID:null
Type Language:http://www.w3.org/2001/XMLSchema
BUILD SUCCESSFUL (total time: 0 seconds)
My issue is that why I am getting Svc ID as "null" when the same is working for Task Name.
Please note:
1. I am using MOXy for JAXB
2. Please note that when I change the sequence then names are getting set to null:
#XmlPath("bpmn:process/bpmn:serviceTask/#id")
#XmlAttribute
List<String> id;
#XmlPath("bpmn:process/bpmn:serviceTask/#name")
#XmlAttribute
List<String> name;
I am getting this output:
run:
JAXB.....org.eclipse.persistence.jaxb.JAXBContext#18eed359
Task Name:null
Svc ID:[ServiceTask_0ip6tj7, ServiceTask_11t11da, ServiceTask_11t11da]
Type Language:http://www.w3.org/2001/XMLSchema
BUILD SUCCESSFUL (total time: 0 seconds)
Looks like mulltiple attributes on Moxy is not supported (What a shame :( I just started to love MOXy)
Attached is a link
With MOXy and XPath, is it possible to unmarshal two lists of attributes?
I'm writing functional tests using Geb and Spock, and building with Maven using GMavenPlus. How can I configure Log4J to to print the line numbers from my Groovy source files? This is my current log4j.properties
log4j.rootLogger=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%-p] %d{dd-MM-yyyy HH:mm:ss} %c:%L - %m%n
Currently this results in messages that look like
[INFO] 2015-07-28 14:13:51,589 Log4jExample:? - Some useful message
This can be reproduced in this small example
#Grab(group='log4j', module='log4j', version='1.2.17')
import org.apache.log4j.*
#groovy.util.logging.Log4j
class Log4jExample {
static void main(def args) {
log.level = Level.INFO
log.removeAllAppenders()
log.addAppender(new ConsoleAppender(new PatternLayout("[%-p] %d %c:%L - %m%n")))
log.info "Some useful message"
}
}
One solutions is to add the #CompileStatic annotation
Your example it would look like
#Grab(group='log4j', module='log4j', version='1.2.17')
import org.apache.log4j.*
#groovy.util.logging.Log4j
#CompileStatic
class Log4jExample {
static void main(def args) {
log.level = Level.INFO
log.removeAllAppenders()
log.addAppender(new ConsoleAppender(new PatternLayout("[%-p] %d %c:%L - %m%n")))
log.info "Some useful message"
}
}
Note that by using #CompileStatic the Groovy meta object protocol will be bypassed.
log4j.properties
log4j.rootLogger=ON, A1
log4j.logger.org.apache.jsp=DEBUG
log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.File=test.log
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] - %m%n
test.java
package ch15;
import org.apache.log4j.Logger;
public class test
{
static Logger logger = Logger.getLogger(test.class);
public static void main(String[] args)
{
makeLog();
}
public static String makeLog()
{
logger.debug("test");
return "YES";
}
}
When I compile this java file and execute, Log File created Normally.
[2013-05-10 16:53:24] - test
But when I intend to use this class file in JSP like below, there's no Log at all.
<jsp:useBean id="t" class="ch15.test" />
<%=t.makeLog()%>
I think JSP call test class successfully because browser displays "YES".
But no log written...
Can you help me?
I'm in trouble for a week...:(