Need information related to sshj library. How logging works? - java

I'm trying to transfer a file from one server to other server using sftp protocol. So, I'm trying to use sshj library for this. Now before transferring the file I'm performing several activities such as zipping and after transferring unzipping . So, I'm logging this details to successLog and if ay error to FailureLog.
here is my log4j properties:-
# Define the root logger
log4j.rootLogger = DEBUG, toConsole
# Define the console appender
log4j.appender.toConsole=org.apache.log4j.ConsoleAppender
log4j.appender.toConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.toConsoleAppender.layout.ConversionPattern=%d{HH:mm:ss} %5p [%t] - %c.%M - %m%n
# Define the file appender
log4j.appender.success=org.apache.log4j.FileAppender
log4j.appender.success.File=logs/success.log
log4j.appender.success.Append=false
log4j.appender.success.layout=org.apache.log4j.PatternLayout
log4j.appender.success.layout.conversionPattern=%d{HH:mm:ss} %5p [%t] - %c.%M - %m%n
# Define the file appender
log4j.appender.failure=org.apache.log4j.FileAppender
log4j.appender.failure.File=logs/failure.log
log4j.appender.failure.Append=false
log4j.appender.failure.layout=org.apache.log4j.PatternLayout
log4j.appender.failure.layout.conversionPattern=%d{HH:mm:ss} %5p [%t] - %c.%M - %m%n
log4j.category.successLogger=DEBUG, success
log4j.additivity.successLogger=true
log4j.category.failureLogger=WARN, failure
log4j.additivity.failureLogger=false
and in java code I'm using this as :-
static final Logger successLog = Logger.getLogger("successLogger");
static final Logger failureLog = Logger.getLogger("failureLogger");
and example failureLog.error("exception occured due to so an so reason",e);
now I would like to store sshj library log in some file called sftp.log. How can I do that??so far I was manually logging into success and failure logs but sshj log is by default printing on console which I want to write it to some file.

Here's my example of writing the SFTP-session FINE-level log to file:
private void enableFineLogging() {
try {
fileHandler = new FileHandler(
"./logs/fine_sshj.log",
10000000, 1000, true);
fileHandler.setLevel(Level.FINER);
fileHandler.setFormatter(new SimpleFormatter());
final Logger app = Logger.getLogger("net.schmizz");
app.setLevel(Level.FINER);
app.addHandler(fileHandler);
app.setUseParentHandlers(false);
app.info(
"######################################################################## "
+ "START LOGGING NEW SSHJ SESSION "
+ "########################################################################");
} catch (Exception e) {
// Do something...
}
}
Though I'm not sure if are able to separate the log levels so that successLogger would have only the success cases... I think there will be also WARNING and SEVERE level messages.

Related

Log4J API not printing messages in the java program

I am trying to implement Log4J API in my java project.
To do that, I have created a properties as shown in the image below (highlighted in yellow):
Project Structure Image
These are the properties I set in the file:
# TRACE < DEBUG < INFO < WARN < FATAL
log4j.rootLogger=TRACE, DEBUG, INFO, file
# Console
# log4j.appender.toConsole=org.apache.log4j.ConsoleAppender
# log4j.appender.toConsole.layout=org.apache.log4j.PatternLayout
# log4j.appender.toConsole.layout.ConversionPatter=%d{HH:mm:ss} %5p [%t] - $c.%M - %m%n
# Redirecting log messages to console
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
I declared the LOGGER object in my class as following:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Credits{
Logger LOGGER = null;
public Credits(String sources) {
LOGGER = Logger.getLogger(ChunkRecon.class.getName());
LOGGER.setLevel(Level.DEBUG);
String creditNames = "select tablename, creditNumbers, credit_type from schema.table where credit_type in ("sources")";
LOGGER.debug("This is a debug message");
system.out.println("This message is from println");
}
}
In the output, I see the message from sysout: This message is from println but not the debug message.
Could anyone let me know what is the mistake I am doing here ?
Try to rename your loggerproperties to log4j.properties and check it is in classpath. Another problem with rootLogger, see explanation here
Also Logger is usually used as static variable. For example:
public class Credits {
private static final Logger logger = Logger.getLogger(Credits.class);
public Credits(String sources) {
logger.setLevel(Level.DEBUG);
logger.debug("This is a debug message");
System.out.println("This message is from println");
}
}
log4j.properties
log4j.rootLogger=debug, stdout
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Your log4j.rootLogger declaration seems incorrect. Try as -
log4j.rootLogger=TRACE,stdout,file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
If you only want the logs on console then remove file logging fully.
log4j.rootLogger=TRACE,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
Refer section Configuring loggers from JavaDoc.
The syntax for configuring the root logger is:
log4j.rootLogger=[level], appenderName, appenderName, ...

Using log4j JMSAppender with ActiveMQ - wire format timeout in debug level (client side)

I'm trying to make a POC using log4j JMSappender and ActiveMQ. I successfully follow this example -> http://activemq.apache.org/how-do-i-use-log4j-jms-appender-with-activemq.html
But this is for INFO level. I made some modification to use it in DEBUG level and my program and activeMQ can't exchange their wire format. Here are my log4j (client side)
log4j.rootLogger=DEBUG, stdout, jms
log4j.logger.org.apache.activemq=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n
log4j.appender.stdout.Threshold=INFO
log4j.appender.jms=org.apache.log4j.net.JMSAppender
log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitialContextFactory
log4j.appender.jms.ProviderURL=tcp://localhost:61616
log4j.appender.jms.TopicBindingName=logTopic
log4j.appender.jms.TopicConnectionFactoryBindingName=ConnectionFactory
log4j.appender.jms.Threshold=DEBUG
When running my client, I have the wire format error.
Producer program:
import org.apache.log4j.Logger;
public class ProducerDebug {
public static void main( String[] args ) throws InterruptedException
{
new ProducerDebug();
}
private ProducerDebug() throws InterruptedException {
Logger logger = Logger.getLogger(ProducerInfo.class);
while (true)
{
logger.debug("push DEBUG");
logger.info("push INFO2");
Thread.sleep(10000);
}
}
}
And the error message:
log4j:ERROR Error while activating options for appender named [jms].
javax.jms.JMSException: Wire format negotiation timeout: peer did not
send his wire format. at
org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:72)
at
org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1412)
at
org.apache.activemq.ActiveMQConnection.ensureConnectionInfoSent(ActiveMQConnection.java:1501)
at
org.apache.activemq.ActiveMQConnection.createSession(ActiveMQConnection.java:323)
at
org.apache.activemq.ActiveMQConnection.createTopicSession(ActiveMQConnection.java:1134)
at
org.apache.log4j.net.JMSAppender.activateOptions(JMSAppender.java:218)
at
org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307)
at
org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:172)
at
org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:104)
at
org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:842)
at
org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:768)
at
org.apache.log4j.PropertyConfigurator.configureRootCategory(PropertyConfigurator.java:648)
at
org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:514)
at
org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:580)
at
org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:526)
at org.apache.log4j.LogManager.(LogManager.java:127) at
org.apache.log4j.Logger.getLogger(Logger.java:117) at
awg.adb.producer.ProducerDebug.(ProducerDebug.java:13) at
awg.adb.producer.ProducerDebug.main(ProducerDebug.java:9) Caused by:
java.io.IOException: Wire format negotiation timeout: peer did not
send his wire format. at
org.apache.activemq.transport.WireFormatNegotiator.oneway(WireFormatNegotiator.java:98)
at
org.apache.activemq.transport.MutexTransport.oneway(MutexTransport.java:68)
at
org.apache.activemq.transport.ResponseCorrelator.asyncRequest(ResponseCorrelator.java:81)
at
org.apache.activemq.transport.ResponseCorrelator.request(ResponseCorrelator.java:86)
at
org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1387)
... 17 more
I tried many things and I cannot understand why I have this error.
For information: I'm using
- ActiveMQ 5.12.1
- Log4j 1.2.17
yes it is due to AMQ logs if level is debug, one solution is to do the opposite like this :
log4j.rootLogger=INFO, stdout
## Be sure that ActiveMQ messages are not logged to 'jms' appender
log4j.logger.org.apache=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n
## Configure 'jms' appender. You'll also need jndi.properties file in order to make it work
log4j.appender.jms=org.apache.log4j.net.JMSAppender
log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitialContextFactory
log4j.appender.jms.ProviderURL=tcp://localhost:61616
log4j.appender.jms.TopicBindingName=logTopic
log4j.appender.jms.TopicConnectionFactoryBindingName=ConnectionFactory
log4j.appender.jms.Threshold=DEBUG
log4j.logger.your.package=jms

Write multiple log4j files with different info

The API I am working on cannot be connected to a database, but need to log events that are happening in the API. To do this I was thinking on using log4j to create log file with API event information.
The problem is that all log entries end up in both logs, and not separated.
Requirements I am need to fulfill
Multiple log files with certain information inside
Backup log files live indefinitely
Log4j properties file
log4j.rootLogger=QuietAppender, LoudAppender, FirstLog, SecondLog, TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=${wls.logs-path}/test-api/test-api-info.log
log4j.appender.QuietAppender.MaxFileSize=512KB
log4j.appender.QuietAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.QuietAppender.layout.ConversionPattern=%d %p [%c] - %m%n
# Keep three backup files.
log4j.appender.QuietAppender.MaxBackupIndex=100
# Pattern to output: date priority [category] - message
log4j.appender.QuietAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.QuietAppender.layout.ConversionPattern=%d %p [%c] - %m%n
# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=${wls.logs-path}/test-api/test-api-debug.log
log4j.appender.LoudAppender.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.LoudAppender.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.LoudAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.LoudAppender.layout.ConversionPattern=%d %p [%c] - %m%n
# setup FirstLog
log4j.appender.FirstLog=org.apache.log4j.RollingFileAppender
log4j.appender.FirstLog.Threshold=INFO
log4j.appender.FirstLog.File=${wls.logs-path}/test-api/first-info.log
log4j.appender.FirstLog.MaxFileSize=10240kB
log4j.appender.FirstLog.MaxBackupIndex=99999
log4j.appender.FirstLog.layout=org.apache.log4j.PatternLayout
log4j.appender.FirstLog.layout.ConversionPattern=%d %p [%c] - %m%n
# setup SecondLog
log4j.appender.SecondLog=org.apache.log4j.RollingFileAppender
log4j.appender.SecondLog.Threshold=INFO
log4j.appender.SecondLog.File=${wls.logs-path}/test-api/second-info.log
log4j.appender.SecondLog.MaxFileSize=10240kB
log4j.appender.SecondLog.MaxBackupIndex=99999
log4j.appender.SecondLog.layout=org.apache.log4j.PatternLayout
log4j.appender.SecondLog.layout.ConversionPattern=%d %p [%c] - %m%n
Java Class
private static final Logger logkp = Logger.getLogger("FirstLog");
private static final Logger logda = Logger.getLogger("SecondLog");
logkp.info(sb.toString());
logda.info(sb.toString());
Current Results
2015-05-27 10:27:46,175 INFO [SecondLog] - 12645,APIServer1,0,000bdc5000000100011055042d0114a6
2015-05-27 10:27:46,583 INFO [FirstLog] - APIServer1,Caller,test-Version-1.0,certValue,1
2015-05-27 10:28:22,458 INFO [SecondLog] - 12645,APIServer1,0,000bdc5000000100011055042d0114a6
2015-05-27 10:28:22,793 INFO [FirstLog] - APIServer1,Caller,test-Version-1.0,certValue,1
2015-05-27 10:28:25,203 INFO [SecondLog] - 12645,APIServer1,0,000bdc5000000100011055042d0114a6
2015-05-27 10:28:25,528 INFO [FirstLog] - APIServer1,Caller,test-Version-1.0,certValue,1
2015-05-27 10:28:26,686 INFO [SecondLog] - 12645,APIServer1,0,000bdc5000000100011055042d0114a6
I'm not 100% sure about this, because it's been a while that I was using log4j and we used to write the configuration in xml, but I think you have to create loggers like this:
log4j.rootLogger=QuietAppender, LoudAppender, TRACE
log4j.logger.FirstLogger = FirstLog, INFO
log4j.additivity.FirstLogger = false
log4j.logger.SecondLogger = SecondLog, INFO
log4j.additivity.SecondLogger = false
... // then configure appenders as you did
To get the outputs you want. Setting the additivity to false "cuts" the connection to the rootLogger. It is set to true by default and will cause all logmessages to be appended to the logger and to all ancestors of the logger. Setting it to false will change that.
If your API has its own namespace - let's say "my.own.API" then you could also create an API-Logger like this:
log4j.logger.my.own.API = MyAPIAppender, INFO
log4j.additivity.my.own.API = false
And create loggers like this:
package my.own.API
public class MyAPIClass{
private static Logger apiLog = Logger.getLogger(MyAPIClass.class);
// ...
}

Log4j: Unable to send mail using Log4j SMTP Appenders

I need to send a email when any Exception occurs in log file .This is my log4j.properties file
log4j.rootLogger=Info, EMAIL
# EMAIL
log4j.appender.EMAIL=org.apache.log4j.net.SMTPAppender
log4j.appender.EMAIL.SMTPHost=smtp.gmail.com
log4j.appender.EMAIL.SMTPProtocol=smtp
log4j.appender.EMAIL.SMTPPort=25
log4j.appender.EMAIL.StartTls=true
log4j.appender.EMAIL.From=krn1231#gmail.com
log4j.appender.EMAIL.To=krn1231#gmail.com
log4j.appender.EMAIL.SMTPUsername=krn1231
log4j.appender.EMAIL.SMTPPassword=mypassword
log4j.appender.EMAIL.Subject=Test Gmail Smtp
log4j.appender.EMAIL.layout=org.apache.log4j.PatternLayout
log4j.appender.EMAIL.layout.ConversionPattern=[%d] [%t] %-5p %c %x - %m%n
log4j.appender.EMAIL.Threshold=ERROR
log4j.appender.EMAIL.BufferSize=1
log4j.appender.EMAIL.SMTPDebug=true
This is my sample Program for Testing this
import org.apache.log4j.Logger;
public class Test {
private static Logger loggers = Logger.getLogger(Test.class);
public static void main(String args[]) {
try {
loggers.info("Hisas");
throw new NullPointerException();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I tried all ways of trail and Error , but of no use
This is the output given inside Eclipse Console , when i tried
log4j:WARN No such property [startTls] in org.apache.log4j.net.SMTPAppender.
DEBUG: setDebug: JavaMail version 1.4ea
java.lang.NullPointerException
at Test.main(Test.java:11)
When i executed this on command prompt
telnet smtp.gmail.com 25
It responded well with
220 mx.google.com ESMTP f8sm802040pbe.42
pass the vm arguement first i.e -Dmail.smtp.starttls.enable=true
log4j.rootLogger=DEBUG, sendMail
log4j.appender.sendMail=org.apache.log4j.net.SMTPAppender
log4j.appender.sendMail.SMTPProtocol=smtps
log4j.appender.sendMail.Threshold=ERROR
log4j.appender.sendMail.SMTPPort=465
log4j.appender.sendMail.SMTPUsername=xxxx#gmail.com
log4j.appender.sendMail.From=xxxx#gmail.com
log4j.appender.sendMail.SMTPPassword=.........
log4j.appender.sendMail.To=yyyyy#gmail.com
log4j.appender.sendMail.SMTPHost=smtp.gmail.com
log4j.appender.sendMail.Subject=Error Alert
log4j.appender.sendMail.layout=org.apache.log4j.PatternLayout
log4j.appender.sendMail.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss.SSS} [%p] %t %c - %m%n
log4j.appender.sendMail.smtp.starttls.enable=true
log4j.appender.sendMail.smtp.auth=true
log4j.appender.sendMail.BufferSize=1
Try the smtps protocol as Gmail requires SSL.

Log4j logging info messages without logging warn messages

I'm trying to log certain info messages onto a file but as soon as I run the application both warn and info messages are logged. Now, from what I've read from this site, you cannot log one without logging the other. Has anyone tried this before? If so, how did your properties file look like?
My properties file looks like this:
***** Set root logger level to INFO and its two appenders to stdout and R.
log4j.rootLogger=INFO, stdout, R
# ***** stdout is set to be a ConsoleAppender.
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# ***** stdout uses PatternLayout.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# ***** Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%M has started] (%F:%L) - %m%n
/
# ***** R is set to be a RollingFileAppender.
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.R.File="folder where log will be saved"
log4j.appender.R.layout.ConversionPattern=%5p [%m has started] %c{2}.[%x] (%F:%L) %d{yyyy-MM-dd HH:mm:ss} - %m%n
# ***** R uses PatternLayout.
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%5p [%m has started] %c{2}.[%x] (%F:%L) %d{yyyy-MM-dd HH:mm:ss} - %m%n
AFAIK there's no standard way to suppress higher log levels than those you are interested in.
However, you might be able to use a custom appender to do that.
It might look similar to this:
public class MyAppender extends AppenderSkeleton {
protected void append(LoggingEvent event) {
if( event.getLevel() == Level.INFO ) {
//append here, maybe call a nested appender
}
}
}
The log level WARN is higher than INFO, and the logging configuration defines the minimum threshold level to be logged by the appender. So, all messages higher than that level will also be logged.
Hence, the WARN messages are expected. And I don't think you can configure it to the way you want.
If the WARN messages that should not be printed come from a different package than the INFO messages, then you can define different log levels for these packages. The first can specify level ERROR and the second INFO
it should look something like this:
log4j.logger.com.test.something=ERROR
log4j.logger.com.other.package=INFO
cheers
Why do you want to filter the WARN level? As peshkira said, you could use two different loggers for splitting/filtering your log output, or you could use tools like grep for filtering (offline) or you could simply remove the WARN logs from your code if your don't need them anyway.
As far as I understand, advanced filters like LevelMatchFilter and LevelRangeFilter can do the trick for you.
Thing worth keeping in mind though is that using these may require xml config instead of properties: Can't set LevelRangeFilter for log4j

Categories

Resources