Logging to different files using single logging.properties - java

I'm trying to configure the logging.properties file that is shared between multiple applications. I want a specific log file for a class of mine, but I don't want other logs (from other classes) to be included in the file.
How can I achieve this by only modifying the logging.properties file?
I have the following logging.properties file:
############################################################
# Default Logging Configuration File
#
# You can use a different file by specifying a filename
# with the java.util.logging.config.file system property.
# For example java -Djava.util.logging.config.file=myfile
############################################################
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# By default we only configure a ConsoleHandler, which will only
# show messages at the INFO and above levels.
handlers= java.util.logging.ConsoleHandler
# To also add the FileHandler, use the following line instead.
#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler
# Default global logging level.
# This specifies which kinds of events are logged across
# all loggers. For any given facility this global level
# can be overriden by a facility specific level
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level= INFO
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/default.log (all the logs are currently going to this file)
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
my.class.logger.level = INFO (I want this class to log to the file /home/myuser/myclass.log)
other.class.logger.level = ALL

It is possible using pure jdk also (try with jdk 7 or jdk 8).
Just create custom file handler; use that similar to java.util.logging.FileHandler and extend it.
public class JULTestingFileHandler extends FileHandler {
public JULTestingFileHandler() throws IOException, SecurityException
{
super();
}
}
user properties file;
com.xxx.handlers = com.xxx.JULXXXFileHandler
com.xxx.JULXXXFileHandler.pattern = ./logs/test1_test2.%u.%g.log

Related

ESAPI:java.lang.ClassNotFoundException: org.owasp.encoder.esapi.ESAPIEncoder Encoder class

I am using ESAPI to encode the string, when using with Oracle JDBC. I Get following error even though i have ESAPI.Properties in my project.
final var queryString =
String.format("SELECT * FROM %1$s WHERE %2$s = '%3$s'",
ESAPI.encoder().encodeForSQL(new OracleCodec(),tableName),
ESAPI.encoder().encodeForSQL(new OracleCodec(),columnName),
ESAPI.encoder().encodeForSQL(new OracleCodec(),columnValue));
Caused by: java.lang.ClassNotFoundException: org.owasp.encoder.esapi.ESAPIEncoder
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:375)
at org.owasp.esapi.util.ObjFactory.loadClassByStringName(ObjFactory.java:158)
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:81)
... 108 common frames omitted
Here is my project structure.
Version:
implementation 'org.owasp.esapi:esapi:2.2.1.1'
here is my ESAPI.properties file
# Properties based on ESAPI 2.2.1.1's configuration/esapi/ESAPI.properties file.
ESAPI.Encoder=org.owasp.encoder.esapi.ESAPIEncoder
# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html
# Note that this is now considered deprecated!
#ESAPI.Logger=org.owasp.esapi.logging.log4j.Log4JLogFactory
# To use JUL, you need to obtain ESAPI's esapi-java-logging.properties and drop
# it somewhere into your class path. You can get it from the ESAPI configuration
# jar. (See Release 2.2.1.1 under GitHub for ESAPI/esapi-java-legacy.)
ESAPI.Logger=org.owasp.esapi.logging.java.JavaLogFactory
# To use the new SLF4J logger in ESAPI (see GitHub issue #129), set
#ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory
# and do whatever other normal SLF4J configuration that you normally would do for your application.
# Note: The uncommented out ones are those needed for SLF4J. Others may be
# needed if you change the ESAPI logger.
#===========================================================================
# ESAPI Logging
# Set the application name if these logs are combined with other applications
Logger.ApplicationName=sql-service
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
Logger.LogEncodingRequired=false
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
Logger.LogApplicationName=true
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
Logger.LogServerIP=false
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
# want to place it in a specific directory.
#Logger.LogFileName=ESAPI_logging_file
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
#Logger.MaxLogFileSize=10000000
# Determines whether ESAPI should log the user info.
Logger.UserInfo=false
# Determines whether ESAPI should log the session id and client IP
Logger.ClientInfo=false
Any Help would be appreciated.

How can I configure tomcat to log on a different file using log4j?

I'm trying to log certain messages on a different file on my tomcat installation, using log4j, but although it does log on my rootLogger it doesn't do it on the separate file I am creating.
Here is my log4j.properies file, where the file I'm trying to use is dataflow_logging.log:
# Root logger option
log4j.rootLogger=INFO, stdout, mainlogger
# Direct dataflow specific messages to specific file.
log4j.logger.org.estat.nsiws.dataflows=INFO, dataflowlogger
log4j.appender.dataflowlogger=org.apache.log4j.RollingFileAppender
log4j.appender.dataflowlogger.File=${catalina.home}/logs/nsi/dataflow_logging.log
log4j.appender.dataflowlogger.MaxFileSize=10MB
log4j.appender.dataflowlogger.MaxBackupIndex=10
log4j.appender.dataflowlogger.layout=org.apache.log4j.PatternLayout
log4j.appender.dataflowlogger.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Disable dataflow log messages in root logger.
log4j.additivity.org.estat.nsiws.dataflows=false
# Direct main logging messages to standard output.
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{HH:mm:ss,SSS} [%p]: %m%n
# Also direct main logging messages to file.
log4j.appender.mainlogger=org.apache.log4j.RollingFileAppender
log4j.appender.mainlogger.File=${catalina.home}/logs/nsi/nsiws.log
log4j.appender.mainlogger.MaxFileSize=10MB
log4j.appender.mainlogger.MaxBackupIndex=10
log4j.appender.mainlogger.layout=org.apache.log4j.PatternLayout
log4j.appender.mainlogger.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%p]: %m%n
My WebService's properties file:
## This file contains properties for the Web Service
# The absolute path to the logs directory
log.directory=logs/nsi
# The log file prefix
log.file.prefix=nsiws_
# The log file suffix
log.file.suffix=.log
# The prefix of the temporary files created for the buffering of responses.
tempfile.buffer.prefix=ws_resp
# Enable logging dataflow access
log.df.file.activation=true
# The absolute path to the dataflow logs directory
log.df.file.directory=logs/nsi
# The dataflow log file prefix
log.df.file.name=dataflow_logging
# The dataflow log file maximum size
log.df.file.max.size=100MB
# The dataflow max backup file
log.df.file.max.backup=10
# The dataflow log file separator
log.df.file.separator=;
# The dataflow log file date pattern
log.df.date.pattern=%d{yyyy-MM-dd HH:mm:ss,SSS};%m%n
The method that initialises the dataflow logger:
private static Logger initDataflowLogger() {
Logger dflogger = null;
try {
if (Boolean.parseBoolean(nsiProps.getProperty("log.df.file.activation"))) {
dflogger = org.apache.log4j.Logger.getLogger("org.estat.nsiws.dataflows");
dflogger.setLevel(Level.INFO);
logger.debug("Initializing dataflow logging...");
}
} catch (Exception e) {
logger.error(getInstance().getMessage("error.df.log.properties.not.set"));
}
return dflogger;
}
Thanks a lot for your help!
Check if this expression is true and if you have set your properties file correctly, so your project can read from it.
Boolean.parseBoolean(nsiProps.getProperty("log.df.file.activation"))
Your root logger is in INFO mode.
Which will not log the debug level statement.
You have taken the instance of org.estat.nsiws.dataflows (dataflowlogger Appender), which is "dflogger" but you are actually calling "logger.debug"

WrapperManager cannot be resolved error: Java Service Wrapper

I am trying to implement the example given here: http://benjsicam.me/blog/running-a-java-application-as-a-windows-service-part-1-tutorial/
The code basically turns a Java application into a service. The application outputs Date and Time to the console at specific intervals. The whole project gets exported to a runnable JAR file, with required libraries in a separate folder. All I have to do is modify the wrapper.conf file to run Main.jar (which is the exported JAR) and put the exported libraries in the lib folder.
I have followed everything exactly, but I am getting the following problem: WrapperManager cannot be resolved. I am including the links for snapshots which show the Maven project structure, the contents of POM.xml, and code contents of four Java files. Also included are the required source files in Google Drive.
Java version jdk1.8.0_11
Main.java
Google Drive Link
Error Shown:
Wrapper.conf file (removed most of the comments+top part)
wrapper.java.mainclass=batch_Proc.main_prog.Main
# Java Classpath (include wrapper.jar) Add class path elements as
# needed starting from 1
wrapper.java.classpath.1=../lib/wrapper.jar
wrapper.java.classpath.2=../lib/aopalliance-1.0.jar
wrapper.java.classpath.3=../lib/commons-logging-1.1.1.jar
wrapper.java.classpath.4=../lib/spring-aop-3.2.1.RELEASE.jar
wrapper.java.classpath.5=../lib/spring-beans-3.2.1.RELEASE.jar
wrapper.java.classpath.6=../lib/spring-context-3.2.1.RELEASE.jar
wrapper.java.classpath.7=../lib/spring-context-support-3.2.1.RELEASE.jar
wrapper.java.classpath.8=../lib/spring-core-3.2.1.RELEASE.jar
wrapper.java.classpath.9=../lib/spring-expression-3.2.1.RELEASE.jar
wrapper.java.classpath.10=../lib/spring-web-3.2.1.RELEASE.jar
wrapper.java.classpath.11=../lib/wrappertest.jar
wrapper.java.classpath.12=Main.jar
# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=../lib
# Java Bits. On applicable platforms, tells the JVM to run in 32 or 64-bit mode.
wrapper.java.additional.auto_bits=FALSE
# Java Additional Parameters
wrapper.java.additional.1=
# Initial Java Heap Size (in MB)
#wrapper.java.initmemory=3
# Maximum Java Heap Size (in MB)
#wrapper.java.maxmemory=64
# Application parameters. Add parameters as needed starting from 1
#wrapper.app.parameter.1=
#********************************************************************
# Wrapper Logging Properties
#********************************************************************
# Enables Debug output from the Wrapper.
wrapper.debug=FALSE
# Format of output for the console. (See docs for formats)
wrapper.console.format=PM
# Log Level for console output. (See docs for log levels)
wrapper.console.loglevel=INFO
# Log file to use for wrapper output logging.
wrapper.logfile=../logs/wrapper.log
# Format of output for the log file. (See docs for formats)
wrapper.logfile.format=LPTM
# Log Level for log file output. (See docs for log levels)
wrapper.logfile.loglevel=INFO
# Maximum size that the log file will be allowed to grow to before
# the log is rolled. Size is specified in bytes. The default value
# of 0, disables log rolling. May abbreviate with the 'k' (kb) or
# 'm' (mb) suffix. For example: 10m = 10 megabytes.
wrapper.logfile.maxsize=0
# Maximum number of rolled log files which will be allowed before old
# files are deleted. The default value of 0 implies no limit.
wrapper.logfile.maxfiles=0
# Log Level for sys/event log output. (See docs for log levels)
wrapper.syslog.loglevel=NONE
#********************************************************************
# Wrapper General Properties
#********************************************************************
# Allow for the use of non-contiguous numbered properties
wrapper.ignore_sequence_gaps=TRUE
# Do not start if the pid file already exists.
wrapper.pidfile.strict=TRUE
# Title to use when running as a console
wrapper.console.title=Test Wrapper Sample Application
#********************************************************************
# Wrapper JVM Checks
#********************************************************************
# Detect DeadLocked Threads in the JVM. (Requires Standard Edition)
wrapper.check.deadlock=TRUE
wrapper.check.deadlock.interval=10
wrapper.check.deadlock.action=RESTART
wrapper.check.deadlock.output=FULL
# Out Of Memory detection.
# (Ignore output from dumping the configuration to the console. This is only needed by the TestWrapper sample application.)
wrapper.filter.trigger.999=wrapper.filter.trigger.*java.lang.OutOfMemoryError
wrapper.filter.allow_wildcards.999=TRUE
wrapper.filter.action.999=NONE
# Ignore -verbose:class output to avoid false positives.
wrapper.filter.trigger.1000=[Loaded java.lang.OutOfMemoryError
wrapper.filter.action.1000=NONE
# (Simple match)
wrapper.filter.trigger.1001=java.lang.OutOfMemoryError
# (Only match text in stack traces if -XX:+PrintClassHistogram is being used.)
#wrapper.filter.trigger.1001=Exception in thread "*" java.lang.OutOfMemoryError
#wrapper.filter.allow_wildcards.1001=TRUE
wrapper.filter.action.1001=RESTART
wrapper.filter.message.1001=The JVM has run out of memory.
#********************************************************************
# Wrapper Email Notifications. (Requires Professional Edition)
#********************************************************************
# Common Event Email settings.
#wrapper.event.default.email.debug=TRUE
#wrapper.event.default.email.smtp.host=<SMTP_Host>
#wrapper.event.default.email.smtp.port=25
#wrapper.event.default.email.subject=[%WRAPPER_HOSTNAME%:%WRAPPER_NAME%:%WRAPPER_EVENT_NAME%] Event Notification
#wrapper.event.default.email.sender=<Sender email>
#wrapper.event.default.email.recipient=<Recipient email>
# Configure the log attached to event emails.
#wrapper.event.default.email.attach_log=TRUE
#wrapper.event.default.email.maillog.lines=50
#wrapper.event.default.email.maillog.format=LPTM
#wrapper.event.default.email.maillog.loglevel=INFO
# Enable specific event emails.
#wrapper.event.wrapper_start.email=TRUE
#wrapper.event.jvm_prelaunch.email=TRUE
#wrapper.event.jvm_start.email=TRUE
#wrapper.event.jvm_started.email=TRUE
#wrapper.event.jvm_deadlock.email=TRUE
#wrapper.event.jvm_stop.email=TRUE
#wrapper.event.jvm_stopped.email=TRUE
#wrapper.event.jvm_restart.email=TRUE
#wrapper.event.jvm_failed_invocation.email=TRUE
#wrapper.event.jvm_max_failed_invocations.email=TRUE
#wrapper.event.jvm_kill.email=TRUE
#wrapper.event.jvm_killed.email=TRUE
#wrapper.event.jvm_unexpected_exit.email=TRUE
#wrapper.event.wrapper_stop.email=TRUE
# Specify custom mail content
wrapper.event.jvm_restart.email.body=The JVM was restarted.\n\nPlease check on its status.\n
# Name of the service
wrapper.name=JavaWindowsServiceSample
# Display name of the service
wrapper.displayname=Java Windows Service Sample
# Description of the service
wrapper.description=A sample java windows service application
# Service dependencies. Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=
# Mode in which the service is installed. AUTO_START, DELAY_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START
# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false
I solved this problem! I had made a simple mistake of not making sure the correct dependencies were downloaded in Maven.
The required jars for WrapperManager and WrapperListener were not available which were causing the errors.

Logger logs are not showing up in Console and Tomcat logs

Well I have my Tomcat logging configured and I know the properties are being read, because it now genereates the log files according to the name prefix that I specified. Well the problems is that the log files contain all the info that Tomcat itself logs, however it doesn't contain anything from what I try to output in my servlet classes with log.info(...) etc
my logging.properties:
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINEST
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = GDIA_
java.util.logging.ConsoleHandler.level = FINEST
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
As you can see it's all set as visible from FINEST, however I don't see any output when i do:
My imports:
import java.util.logging.Level;
import java.util.logging.Logger;
My log variable:
private final static Logger log = Logger.getLogger(GenTreeUploader.class.getName());
My testing the output:
log.severe("GREAT!!!!!!!!!!");
I'm running Tomcat 7 in Eclipse. What's interesting is that before I added configuration to tomcat run configuration in eclipse The log output would work fine to console, but whenever I added this:
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.util.logging.config.file=D:\Dropbox\EclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp7\conf\logging.properties"
I couldn't see any output in console or in the log file. Of course prior to adding this my logging.properties were not to be found...
So any ideas why when I add this configuration I can't see any log output from the application classes when I do "log.severe("GREAT!!!!!!!!!!");"...?

Display FINE log level in output

how can i display the fine log message in output screen in java?
You might want to configure other defaults with a properties file. This allow things to be reconfigured without recompiling.
# Specify the handlers to create in the root logger
# (all loggers are children of the root logger)
# The following creates two handlers
handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler
# Set the default logging level for the root logger
.level = ALL
# Set the default logging level for new ConsoleHandler instances
java.util.logging.ConsoleHandler.level = INFO
# Set the default logging level for new FileHandler instances
java.util.logging.FileHandler.level = ALL
# Set the default formatter for new ConsoleHandler instances
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# Set the default logging level for the logger named com.mycompany
com.mycompany.level = ALL
I prefer this to littering my code with logging configuration calls.
You have to specify the location of the file with a command line option though :
java -Djava.util.logging.config.file=mylogging.properties
I personally always use log4j or slf4j because it looks for a config file in the classpath. Well, maybe java.util.logging does that too, I never really investigated.

Categories

Resources