Log4J Question
Hi,
Does anyone know how to configure Log4J to use a different properties file name to "log4j.properties"? I seem to recall seeing somewhere that this could be controlled by setting a system property, but can't find any info on it anymore.
Thx
D
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
PropertyConfigurator.configure(
ClassLoader.getSystemResource( "ANYNAME.properties" ) );
Similar Messages
-
General log4j question I can't answer myself
I have developed an app using Eclipse that uses log4j and everything seems to work fine. But when I copy the code to our Unix box and run it with Ant (just upgraded to 1.7 if that makes a difference), all the logging gets redirected to stdout. It WAS working at some point, but now I can't seem to get it to work correctly and I think it has something to do with the location of my log4j.properties file. Where does this darn thing go? I jar the project if that makes any difference.
Should it go in the same directory as the Main class? same dir as the base dir? current dir? Inside the jar? outside? etc...
my directory structure is:
ls .
build.xml
classes (dir)
build (dir)
src(dir)
ls build
MyProgram.jar
so I call Ant from .
And as a second question, does eclipse do any voodoo to get the pull the config file?I have developed an app using Eclipse that uses log4j
and everything seems to work fine. But when I copy
the code to our Unix box and run it with Ant (just
upgraded to 1.7 if that makes a difference), all the
logging gets redirected to stdout. It WAS working at
some point, but now I can't seem to get it to work
correctly and I think it has something to do with the
location of my log4j.properties file. Where does
this darn thing go? I jar the project if that makes
any difference.
Should it go in the same directory as the Main class?
same dir as the base dir? current dir? Inside the
jar? outside? etc...Question the first: What are we talking about here, a web app, desktop (swing) app or something else?
>
my directory structure is:
ls .
build.xml
classes (dir)
build (dir)
src(dir)
ls build
MyProgram.jar
so I call Ant from .
And as a second question, does eclipse do any voodoo
to get the pull the config file?No it doesn't. It only does what you tell it to though you may do so inadvertantly.
The rough answer to your first question is that it doesn't really matter so long as the file system can find it. Likely this can be corrected with a handy path entry though you need to be wary that you don't have multiple files referenced in your path that have the same name.
Knowing more about what you're deploying, and how you're deploying it would be helpful in trying to give you better answers.
PS. -
RollingFileAppender/Log4J question (problem with reading logging)
Hi everyone,
I've got a question about log4j.
I'm working with an application that generates a lot of logging. When I'm trying to figure out problems in the application it's hard to read the log files because they get updated/overwritten all the time.
The mechanism of the RollingFileAppender of log4j is that when the maximum file size is reached a new log file is created with <filename>.1 and the name of every file that already existed is increased with 1.
So when I try to read my logfiles they get overwritten while I'm reading it because the application generates a new logfile sometimes 4 times per minute. That's very annoying, so what I would like to have is that everytime a new logfile is created it's number is increased with 1 until a maximum of files and then start over.
I've been trying to find this mechanism somewhere but can't find it. The DailyRollingFileAppender kinda does what I want but you can't set a maximum of files and I can't have that because of the space available on the server.
Does anyone know how to solve this?I've got a question about log4j.
I'm working with an application that generates a lot
of logging. When I'm trying to figure out problems in
the application it's hard to read the log files
because they get updated/overwritten all the time.
The mechanism of the RollingFileAppender of log4j is
that when the maximum file size is reached a new log
file is created with <filename>.1 and the name of
every file that already existed is increased with 1.
So when I try to read my logfiles they get
overwritten while I'm reading it because the
e application generates a new logfile sometimes 4
times per minute. That's very annoying, so what I
would like to have is that everytime a new logfile is
created it's number is increased with 1 until a
maximum of files and then start over.That's not Log4J's problem. That's your problem for treating log files like production data. Maybe you need to use something else, like writing this supposedly persistent data to a database.
I've been trying to find this mechanism somewhere but
can't find it. The DailyRollingFileAppender kinda
does what I want but you can't set a maximum of files
and I can't have that because of the space available
on the server.What stops you from introducing another periodic process, to purge old log files? That's what most would do. -
Log4j question about closed appender error
Hi all,
In my company's project, we have used the log4j 1.1.3 for logging. Since in the project, there are a few applications. We have a common properties to state the log4j properties for AppSTDERR(console), AppLogFile and AppNTEventLog. And we also have a properties file for each application. In each proeprties file, we state a different path to the AppLogFile for different application. We use PropertyConfigurator.configure() to configure the properties and use Category.getRoot(). However, sometimes some application's log will log to another application log file. So we decide to change the application properties file like this:
log4j.category.AppXXX=DEBUG, AppXXXSTDERR, AppXXXLogFile
log4j.appender.AppXXXLogFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.AppXXXLogFile.File=C:\\xxx\\xxx.log
log4j.appender.AppXXXLogFile.layout=org.apache.log4j.PatternLayout
log4j.appender.AppXXXLogFile.layout.ConversionPattern=%d{ISO8601} [%-5p] [%t] %m%n
log4j.appender.AppXXXSTDERR: org.apache.log4j.ConsoleAppender
log4j.appender.AppXXXSTDERR.layout: org.apache.log4j.PatternLayout
log4j.appender.AppXXXSTDERR.layout.ConversionPattern: %d{ISO8601} [%-5p] [%t] - %m%n
We don't use Category.getRoot() and use Category.getInstance("AppXXX") instead. But we sometimes get these errors on console:
log4j:ERROR Attempted to append to closed appender named [AppSTDERR].
log4j:WARN Not allowed to write to a closed appender.
log4j:ERROR Attempted to append to closed appender named [AppLogFile].
log4j:WARN Not allowed to write to a closed appender.
We don't know what is the problem. We guess that some common programs will log common messages to AppLogFile and AppSTDERR but we do not open the AppLogFile and AppSTDERR in each application. Is that we have to use Category.getRoot() ?
Anybody help?
RaymondDo you not need a DatePattern value for the DailyRollingFileAppender? DatePattern being the variable that determines WHEN the logs are rolled.
If not specified what is the default value? Could not setting this value result in strange behavior?
These are shots in the dark I know but we are having similar issues. I can't find any documentation on what the default value is of DatePattern if not specified and have no idea what happens if no value is set. At any rate we are going to supply a value for DatePattern and see if it fixes our problem, I'll post the resutls. -
Hi,
Can someone please tell me how to write to different files using log4j? The documentation talks about using the addAppender method to add an appender to a logger class. Does anyone know if I can define multiple appenders in the configuration file but only use them for specific instances of a logger?
To try and clarify - I want two different classes to use log4j but I want them to log to different RollingFileAppenders.
Everyone seems to have figured this one out but me :)
Can someone please point me in the right direction?
Thanks,
VaughneOk, let's see...
Say you defined:
In class 1
Category category1 = new Category("first.class.name");In class 2
Category category2 = new Category("other.class.name");(It is common use to have the Category name reflect the package structure...).
Now, in your configuration file you'd define the relation category-appender, something like that:
(Note that the appenders are define at the bottom of my example.)
(NOTE also that's it's common use to call the PropertyConfigurator as soon as possible.
### categories ###
# Set all categories to their priority and appender.
log4j.category.first.class.name=INFO, ConsoleAppender // logs to console
log4j.category.other.class.name=DEBUG, TraceAppender // logs to file
### ConsoleAppender ###
# The ConsoleAppender is set to be a ConsoleAppender which outputs to System.out.
log4j.appender.ConsoleAppender=org.apache.log4j.ConsoleAppender
# ConsoleAppender uses PatternLayout.
log4j.appender.ConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.ConsoleAppender.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss.SSS} %-5p %-29c - %m%n
### TraceAppender ###
# The TraceAppender is set to be a DailyRollingFileAppender which outputs to a file called logs/trace/trace.log.
log4j.appender.TraceAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.TraceAppender.File=./logs/trace/trace.log
log4j.appender.TraceAppender.DatePattern='.'yyyy-MM-dd
# TraceAppender uses PatternLayout.
log4j.appender.TraceAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.TraceAppender.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss.SSS} %-5p %-29c - %m%n
...;) Patrick -
I need some log4j help. Hope anyone can help me.
Question 1:
I need to log information to 4 different files. As far as I can tell from the log4j docs, I will then need to create 4 different appenders in the log4j.properties file. How can I do that?
Looking at examples, it looks like I will need to add 4 new sections similar to this one. Is that correct?
# Logfile 1
log4j.appender.log1=org.apache.log4j.RollingFileAppender
log4j.appender.log1.File=C:/Sun/logs/logme1.log
Question 2:
After that is done, how can I actually write to the files? When logging I was thinking just using: logger.info("log something").
How can I specify which file that will log to? Is that even the correct way to log?
Hope someone can help!After that is done, how can I actually write to the files? When logging I
was thinking just using: logger.info("log something").
How can I specify which file that will log to? Is that even the correct
way to log?apperantly, it doesn't seem like you have understand how log4j works. that's probably why warnerja tell you to perform some search.
understand the technology first..then ask specific question here.
it will be useless just handling out answers to everyone. i think they're here just not to provides answers, but to educate other along the way...but they need to see an effort was made first.
you're right..there are time when one doesn't have enough time to understand the whole technology..or the technology is too difficult to comprehend..or the documentation is poor., but i think there are plenty of good documentation on log4j. Futhermore..what you are asking is not usually shown in the documentation, but a google search would probably provides you with the answer you seek..you just need to find a good keyword.
Futhermore, I suggest you read some tutorial on log4j if you plan to use the technology..it will not takes all day..maybe an hour or so..just to get how the technology works
anyway,
your appender tell the logger where the log the message to (depends on the level you specified) .. so if you have 3 appender that specified
the level to be INFO, and you have logger.info("This is an INFO message"), then the message will be log to all three files.
log4j.threshold=ALL
log4j.rootLogger=ALL, stdout, DebugAppender, InfoAppender,
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c %d{ISO8601} -- %p -- %m%n
log4j.logger.DebugAppender.access=DEBUG
log4j.appender.DebugAppender=org.apache.log4j.RollingFileAppender
log4j.appender.DebugAppender.File=.${file.separator}log${file.separator}ex_debug.log
log4j.appender.DebugAppender.MaxFileSize=10KB
log4j.appender.DebugAppender.MaxBackupIndex=1
log4j.appender.DebugAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.DebugAppender.layout.ConversionPattern=%c %d{ISO8601} -- %p --
%m%n
log4j.logger.InfoAppender.access=INFO
log4j.appender.InfoAppender=org.apache.log4j.RollingFileAppender
log4j.appender.InfoAppender.File=.${file.separator}log${file.separator}ex_info.log
log4j.appender.InfoAppender.MaxFileSize=10MB
log4j.appender.InfoAppender.MaxBackupIndex=2
log4j.appender.InfoAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.InfoAppender.layout.ConversionPattern=%c %d{ISO8601} -- %p -- %m%nthe
log4j.rootLogger=
tell what appender to use...so include all your appender in this property.
you appender specified the logging level INFO, WARN, DEBUG,
ERROR, or FATAL. I'm not sure how to specified the min and max level
for an appender using a property file..for xml configuartion file..look at
the example provide in previous reply.
now if you do :
logger.info("This is an info message") and want it to log to file1 and file2
and log.info("This is another info message") and you want this to log to file3
you can't do that...a way around this is to create your own level..and the
appender will specifies that level.
if you plan to use an XML configuration file, then make sure you include the <root> node
<root>
<priority value="debug"/>
<appender-ref ref="DEBUG"/>
<appender-ref ref="INFO"/>
<appender-ref ref="MY_APPENDER_NAME"/>
</root>
</log4j:Configuration> -
A question about log4j.properties
Normally I put the log4j.properties inside my web-application such as under WEB-INF. So it will be packaged into the WAR.
But now I want to take it outside of the WAR and put it under a dir and furthermore I change its name to "myLog4j.log4j.properties". This has two advantages:
1.
One can change the contents without opent the WAR.
2.
Under this dir the other projects can put their xxx.log4j.properties so they can be managed easily.
But I don't know where should I put this file and how to configure the server sothat the server can find this file and my program can write all the log infos into the log-file defined in the "myLog4j.log4j.properties".
Can someone help?
RegardsActually file log4j.properties should be in the classpath, that classloader could see it. Add the path to file into CLASSPATH.
Thanks -
Sorry regarding this query,this is about Log4j.
1.I have downloaded and installed Log4J (version 1.2.15)
C:\Log4J\apache-log4j-1.2.15
2.I have a created a project called 'MyTest' in Eclipse
and the Buildpath(i.e classpath) of this project points
to the Log4j-1.2.15 jar file.)
3 I also need to point the buildpath of this project to the
include the log4j.properties file (which is the the src directory
of my Log4J folder
C:\Log4J\apache-log4j-1.2.15\src\log4j.properties
Can anyone tell me how to include this file in my classpath
for my eclipse project
Project -> properties -> Java Build Path ??
There is no option to include a file here ??
Or have I overlooked any point?ok,got this up and running.It works.
Thanks -
Question about blazeds turnkey, tomcat and directory structure
hi. this question is pretty basic...been reading sujit reddy g's blog on installing/setting up blazeds.
in one article he creates a samplewebapps directory in C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\samplewebapps and copies the blazeds WEB-INF/lib into that directory and the configuration files in the flex folder across as well...http://sujitreddyg.wordpress.com/2009/04/07/setting-up-blazeds/
in another article on invoking java methods from flex he configures the remote-config.xml file directly in the blazeds\WEB-INF\flex folder....http://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-fle x/
wasn't sure why in the first example he copied the files and folders to the samplewebapps directory while in the second example he just configured the files within the blazeds directory...thanx...(i'm a newbie at server side development)I'll take a stab at it. The key thing to realize is the BlazeDS code is ADDED on
to the appserver. E.g. for Tomcat/WebLogic/et al one adds the reference in the web.xml file in WEB-INF.
So, what is that add-on?
1. Executable files. These are jar files and typically stuck into WEB-INF/lib
2. Configuration files. flex/services-config.xml is specified in web.xml. It refers to the other config files in WEB-INF/flex
So, the config in web.xml tells Tomcat (and its forked commercial products) to load up the Flex jars and run some classes. By standard, the "run some classes" follows the servlet lifecycle and runs specific methods in the class when the servlet is loaded, called, destroyed. So, Flex jars have a class which implements the servlet interface.
Incidentally, you may also see references to log4j, Spring, and other frameworks in the web.xml as well. They do the same sort of stuff. So, Tomcat does the passing of the HTTP packets and stages them into Java classes and the hooked in frameworks do add their own behaviours to the setup.
HTH,
TimJowers
P.S> Also note in Flex when you setup the project properties for a Flex Project then you need to match up your URL and "context" to what you have on your server. In his exampe, the "samples" context may have already been setup so easier to use. What is a "context"? The idea is to have more than one webapp running on an appserver. In Tomcat, its basically just the subdirectory under "webapps". That directory name becomes part of the URL. E.g. webapps/samples -> http://localhost:8080/samples or webapps/mytest -> http://localhost:8080/mytest -
Problem in Using Log4J with Weblogic 9.2
I am using Weblogic 9.2 and Log4j.
By using Admin console I set the Severity Level to WARNING and inside my java code is given below:
Logger logger = Log4jLoggingHelper.getLog4jServerLogger();
if (logger.isEnabledFor(Priority.DEBUG)){
logger.debug("DEBUG - Test Debug message");
logger.info("DEBUG - Test Info Message");
logger.warn("DEBUG - Test Warning Message");
logger.error("DEBUG - Test Error Message");
logger.fatal("DEBUG - Test Fatal Message");
Somehow the logger.isEnabledFor(Priority.DEBUG) returning 'TRUE' and the follwoing message is displayed.
<Nov 29, 2006 2:44:04 PM EST> <Warning> org.apache.log4j.Category> <000000> <DEBUG - Test Warning Message>
<Nov 29, 2006 2:44:04 PM EST> <Error> <org.apache.log4j.Category> <000000> <DEBUG - Test Error Message>
<Nov 29, 2006 2:44:04 PM EST> <Info> <org.apache.log4j.Category> <000000> <DEBUG - Test Fatal Message>
<b><i>NOTE - The logger.debug() and logger.info() methods are not invoked because of the severity level to 'WARNING' in the console.</i></b>
<b>I would like to know why the Somehow the logger.isEnabledFor(Priority.DEBUG) is having a value of 'TRUE'.</b>
I expected only the Somehow the logger.isEnabledFor(Priority.ERROR) will have the value of 'TRUE'.Did you get an answer to your question? I have the same problem with WebLogic 10.0.
-
Global variable in servlet & DBPooling questions
Hello guys,
I used to develop PHP/ASP, and am new to servlet. I have been searching around for a solution ...
With Php, we can get the reference of a global variable in any classes->functions...
How do I do this with servlet ?
And second..I have developed the DB class as below... I set the datasource to be static, so it initializes only once. Is it a good idea? How would you like to improve this class? any comments?
package shop.database;
import javax.sql.DataSource;
import java.sql.*;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import shop.admin.exception.GeneralException;
public class DdManager {
static protected Logger logger = Logger.getLogger(DdManager.class);
private String userName = "root";
private String password = "";
private String hostName = "jdbc:mysql://localhost:3306/shop";
private String database="shop";
static private DataSource ds; // set this to be static so all threads share the same job in JVM
private Statement stmt;
private Connection conn;
private ResultSet rs;
private CallableStatement cs;
public DdManager() {}
* setup the data source and return it
public static DataSource getDataSource(
String sDrvName,
String sUserName,
String sPwd,
String connectURI) {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName( sDrvName );
ds.setUsername( sUserName );
ds.setPassword( sPwd );
ds.setUrl( connectURI );
ds.setMaxActive( 15 );
ds.setMaxIdle( 10 );
ds.setMaxWait( 10000 ); // 10 seconds
return ds;
* static init of the class
* this class is will be called only once to initialize the DataSource
static {
try {
Class.forName( "com.mysql.jdbc.Driver" );
ds = getDataSource( "com.mysql.jdbc.Driver",
"root",
"jdbc:mysql://localhost:3306/shop" );
if (ds == null) {
String msg = "Connection Pool error";
logger.error(msg);
throw new GeneralException(msg);
logger.info("DataSource has been initialized");
} catch(Exception exception) {
logger.error(exception.toString());
try {
throw new GeneralException(exception.toString());
} catch (GeneralException e) {
logger.error(e.toString());
* get the connection from the pool (DataSource)
public void openConnection() throws GeneralException {
try {
BasicDataSource bds = (BasicDataSource) ds;
logger.info("NumActive: " + bds.getNumActive() + ", " + "NumIdle: " + bds.getNumIdle());
conn = ds.getConnection();
logger.info("Connection of " + database + " has been established");
} catch(Exception exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
* close the connection will actually return the connection to the pool (Must)
public void closeConnection() throws GeneralException {
initResource();
try {
if (conn != null){
conn.close();
logger.info("Connection of " + database + " has been closed");
} catch(SQLException exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
* prepare the calling stmt
public void prepareProcedure(String callStatement) throws GeneralException {
initResource();
try {
cs = conn.prepareCall(callStatement);
} catch(SQLException exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
* set the pass-in parameter for "String"
public void setParameter(int position, String parameter) throws GeneralException {
try {
cs.setString(position, parameter);
} catch(Exception exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
* set the pass-in parameter for "Integer"
public void setParameter(int position, int parameter) throws GeneralException {
try {
cs.setInt(position, parameter);
} catch(Exception exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
* execute the procedure and return the resultset
public ResultSet execProcedure() throws GeneralException {
try {
rs = cs.executeQuery();
} catch(SQLException exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
return rs;
* close the statment and resultset
private void initResource() throws GeneralException {
try {
if(rs != null) {
rs.close();
if(stmt!= null) {
stmt.close();
logger.info("Statement & Resultset have been free");
} catch(Exception exception) {
logger.error(exception.toString());
throw new GeneralException(exception.toString());
Thanks mates!
myyThanks Saish,
Your response is really appreciated. Sorry about that
as i didnt know there is 'code' formatting button,
and I will look into the Singleton pattern.
As I'm still in the learning stage. Therefore, i
still have a lot of thing do not understand.
... use it in a method signature ...What is "a method signature" ?
A method signature is basically the method's parameters, return value, name and any access or other modifiers. The following is a method signature:
static final public void main(final String[] args)Between the braces of the method body is the implementation (or as I already alluded to, the method body).
Consider using an already-developed connection poolimplementation, such as Jakarta Commons DBCP ...
I'm trying to implement the Jakarta DBCP. Did I go
into the wrong way?
Sorry, did not read the imports. Yes, you are. However, I am confused about what you are trying to implement. You have a static method getDataSource(). You also have a static variable 'ds'. Use one or the other. I would be that there are seemingly random errors cropping up based on whether you remember to call getDataSource() or not.
You do not, generally, want the data source to be static. Multiple threads might use the class. And if there is only a static data source, you will either need to synchronize the methods that use the data source (resulting in a scaling bottleneck) or not synchronize them (which will totally destroy any concept of a logical unit of work or database transaction).
.. A static datasource, as in your class, can onlysafely be used by one thread at a time, potentially
introducing scaling bottlenecks (or race conditions)
in your system ...
So, you mean there is no need for the DataSource to
be static ?
No, in fact, IMO, it should not be. That is why you are pooling. Use instances. The pool will manage the connections and their availabilty for you.
Why are you throwing GeneralException everywhere?Here's a question: can someone using your class (a
caller) realistically be expected to handle a
database exception?
When there is a database error, I just want to stop
the process and redirect the user to an error page. I
will look into the unchecked exceptions. Thanks.
Unchecked exceptions do not need to be declared in a method signature or caught within the method body. Checked exceptions do. As such, an added benefit is that unchecked exceptions de-clutter your code.
In your initResources() method, what happens if theclose() on ResultSet throws an exception
Oh, yes. I'm so stupid.
Now I only have ...
private static DataSource ds; // set this to
be static so all threads share the same obj in JVM
private Connection conn;
private CallableStatement cs;
private void initResource() throws GeneralException
n {
try {
if(cs != null) {
cs.close();
logger.info("CallableStatement has been
as been free");
} catch(Exception exception) {
logger.error(exception.toString());
throw new
throw new GeneralException(exception.toString());
You still have issues.
public void initResources() {
if (rs != null) {
try { rs.close(); } catch (SQLException ignore) { ignore.printStackTrace(); }
if (stmt != null) {
try { stmt.close(); } catch (SQLException ignore) { ignore.printStackTrace(); }
}Normally, this type of method would not be called initResources() but rather closeResources() or freeResources(). It would be called from within the 'finally' block of another method using the CallableStatement or ResultSet.
This is really is problem, would you mind to tell me
how to handle this(close the connection) if the
close() on either CallableStatement or Resultset
throws an exception ?
See above. Simply log the exception (there is usually nothing meaningful you can do if a close() fails, and it is up to you as a developer if this is an error or just a warning). Another option is to 'chain' exceptions. In your own exception, add a method 'addException(Throwable)'. This would add another exception to a List of exceptions. When you print the stack trace, iterate through the chained exceptions to print them all out. One place where I find this useful is rollback() code. If the original SQL statement fails AND the rollback fails, I definitely want to see that rollback() exception as well in my logs.
The DB thing makes me headache. What I actually
wanted is a solution for:
Let say I have a class "HelloAction.class" contains
the code:
public ActionForward XXX() {
DbManager DB = new DBManager();
... do some DB thing here...
SecondClass SC = new SecondClass();
SC.doSomeOtherDbThing();
... do something else...
ThirdClass TC = new ThirdClass();
SC.doMoreOtherDbThing();
}There are some functions in SecondClass.class and
ThirdClass.class that will need database connection.
I consider 'global variable' is because I want these
two classes are able to use the same
connection(DbManager) from the function -
ActionForward XXX().
What is the best way to implement the above situation
(sharing the same connection in different classes &
sub-classes?
I also just realize that the problem of multi-threads
with these two class variables..
private Connection conn;
private CallableStatement cs;Really headache. I really appreciate any comments.
Thanks.
- myyPass the Connection or DataSource to each method or constructor. Call commit() or rollback() from the method that created the transaction.
- Saish -
German Umlauts OK in Test Environment, Question Marks (??) in production
Hi Sun Forums,
I have a simple Java application that uses JFrame for a window, a JTextArea for console output. While running my application in test mode (that is, run locally within Eclipse development environment) the software properly handles all German Umlauts in the JTextArea (also using Log4J to write the same output to file-- that too is OK). In fact, the application is flawless from this perspective.
However, when I deploy the application to multiple environments, the Umlauts are displayed as ??. Deployment is destined for Mac OS X (10.4/10.5) and Windows-based computers. (XP, Vista) with a requirement of Java 1.5 at the minimum.
On the test computer (Mac OS X 10.5), the test environment is OK, but running the application as a runnable jar, german umlauts become question marks ??. I use Jar Bundler on Mac to produce an application object, and Launch4J to build a Windows executables.
I am setting the default encoding to UTF-8 at the start of my app. Other international characters treated OK after deployment (e, a with accents). It seems to be localized to german umlaut type characters where the app fails.
I have encoded my source files as UTF-8 in Eclipse. I am having a hard time understanding what the root cause is. I suspect it is the default encoding on the computer the software is running on. If this is true, then how do I force the application to honor german umlauts?
Thanks very much,
Ryan Allaby
RA-CC.COM
J2EE/Java Developer
Edited by: RyanAllaby on Jul 10, 2009 2:50 PMSo you start with a string called "input"; where did that come from? As far as we know, it could already have been corrupted. ByteBuffer inputBuffer = ByteBuffer.wrap( input.getBytes() ); Here you convert the string to to a byte array using the default encoding. You say you've set the default to UTF-8, but how do you know it worked on the customer's machine? When we advise you not to rely on the default encoding, we don't mean you should override that system property, we mean you should always specify the encoding in your code. There's a getBytes() method that lets you do that.
CharBuffer data = utf8charset.decode( inputBuffer ); Now you decode the byte[] that you think is UTF-8, as UTF-8. If getBytes() did in fact encode the string as UTF-8, this is a wash; you just wasted a lot of time and ended up with the exact same string you started with. On the other hand, if getBytes() used something other than UTF-8, you've just created a load of garbage. ByteBuffer outputBuffer = iso88591charset.encode( data );Next you create yet another byte array, this time using the ISO-8859-1 encoding. If the string was valid to begin with, and the previous steps didn't corrupt it, there could be characters in it that can't be encoded in ISO-8859-1. Those characters will be lost.
byte[] outputData = outputBuffer.array();
return new String( outputData ); Finally, you decode the byte[] once more, this time using the default encoding. As with getBytes(), there's a String constructor that lets you specify the encoding, but it doesn't really matter. For the previous steps to have worked, the default had to be UTF-8. That means you have a byte[] that's encoded as ISO-8859-1 and you're decoding it as UTF-8. What's wrong with this picture?
This whole sequence makes no sense anyway; at best, it's a huge waste of clock cycles. It looks like you're trying to change the encoding of the string, which is impossible. No matter what platform it runs on, Java always uses the same encoding for strings. That encoding is UTF-16, but you don't really need to know that. You should only have to deal with character encodings when your app communicates with something outside itself, like a network or a file system.
What's the real problem you're trying to solve? -
Log4j async appender and line number output
Hello,
I am trying to implement log4j in my application, and would like to log the caller class and the line number of the call. When I do not use async appender, the caller class and the line number are logged. However when I add the same appenders to the AsyncAppender, the caller information is lost. Please, take a look at the config and output snippets.
Thanks,
Elana
======
Here is the configuration without the use of the async appender (Async tags are commented out)
<log4j:configuration debug="true">
<!-- <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="SystemOut"/>
<appender-ref ref="FileOut"/>
</appender>
-->
<appender name="SystemOut" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%5p (%d{DATE}) [%t] (%F:%L) - %m%n"/>
</layout>
</appender>
<appender name="FileOut" class="org.apache.log4j.RollingFileAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%5p (%d{DATE}) [%t] (%F:%L) - %m%n"/>
</layout>
<param name="File" value="logs/exampleAsync.log"/>
<param name="MaxFileSize" value="100KB"/>
<param name="MaxBackupIndex" value="1"/>
</appender>
<root>
<!--<appender-ref ref="ASYNC"/> -->
<appender-ref ref="FileOut"/>
<appender-ref ref="SystemOut"/>
</root>
</log4j:configuration>It produces the following output:
DEBUG (08 Apr 2006 17:03:49,140) [Thread-0] (LogGenerator.java:79) - Debugging
DEBUG (08 Apr 2006 17:03:52,145) [Thread-0] (LogGenerator.java:74) - TracingHere is the configuration WITH the use of async appender
<log4j:configuration debug="true">
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="SystemOut"/>
<appender-ref ref="FileOut"/>
</appender>
<appender name="SystemOut" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%5p (%d{DATE}) [%t] (%F:%L) - %m%n"/>
</layout>
</appender>
<appender name="FileOut" class="org.apache.log4j.RollingFileAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%5p (%d{DATE}) [%t] (%F:%L) - %m%n"/>
</layout>
<param name="File" value="logs/exampleAsync.log"/>
<param name="MaxFileSize" value="100KB"/>
<param name="MaxBackupIndex" value="1"/>
</appender>
<root>
<appender-ref ref="ASYNC"/>
</root>
</log4j:configuration>It produces the following output: (NOTE the question marks in the place of caller info)
DEBUG (08 Apr 2006 17:12:12,534) [Thread-1] (?:?) - Tracing
DEBUG (08 Apr 2006 17:12:15,528) [Thread-1] (?:?) - DebuggingI don't think you can use AsyncAppender with a properties file. You have to use XML and a JoranConfigurator
-
Log4j : how to get log file name and directory
My log4j is working fine. Below is how I define the property file
log4j.rootCategory=DEBUG, A1
log4j.appender.A1=org.apache.log4j.RollingFileAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.A1.File=temp/log.txtI want to know, from my java program, how to retrieve my log file "temp/log.txt" because I want to display at console and notify user where to find the log file.
ThanksOr perhaps I did not understand your requirement. Which of the following is it?
1. Given some Java class, you need to do something with its source code?
2. Given some file whose path is specified by user input or runtime configuration or compile-time constant, you need to do something with that file?
3. Neither of the above?
If 1: Can't do it. Don't need to do it. Don't waste your time trying. Unless you're writing something like a debugger. If so, then if you have to ask this question, you do not have the skills necessary for the broader task.
If 2: Google for java io tutorial. Study it, try some code, and come back with a more specific question if you're still confused.
If 3: Explain clearly what you're trying to accomplish and why you think this approach is the right one. -
Hi,
We are migrating an EJB application from Weblogic 8.1 to Weblogic 10.0
In the current configuration, we simply include the following in the server startup script, so as to specify the log4j configuration file, and this takes care of the logging part.
-Dlog4j.configuration=file:<complete file name>
The same thing doesn't work with WL 10. Is there any other (special) way of using Log4j with WL 10?
Note that inside the code, we use commons-logging to get hold of the logger as follows:-
org.apache.commons.logging.LogFactory.getLog(class)
I would be grateful for any help on this.
Thanks in advance.
Regards,
NeeleshTricky questions.. this problem needs more analysing. I see that you are on R27.6.0, we've come with a few updates to that one. Download the latest greatest and see if that works things out: http://www.oracle.com/technology/software/products/jrockit/index.html. If not, then report this issue to JRockit support (see how to below)!
Best Regards,
Tuva
JRockit PM
How to report to JRockit support:
You must register and file the issue on Metalink, http://metalink.oracle.com. Note that you must have purchased support to continue.
If you have problems during the registration or filing you can call our support +1.800.223.1711* or 1-800-633-0738 directly.
In case you have not purchased support call 1.800.833.3536* for support sales.
More information on our support site: http://www.oracle.com/support/index.html.
*) US numbers - for global technical support contacts see: http://www.oracle.com/support/contact.html
Maybe you are looking for
-
Virtualbox Win7 guest VM runs 1-2 minutes then freezes host
I have a Windows 7 guest running on an Arch Linux host. It was created and ran perfectly for a long while on my old Lenovo Thinkpad T510, but when I moved it to my new W530, this problem started. W530 Specifications Processor: Intel Core i7-3740QM Pr
-
The XP computer is a 5 year old Dell and the Windows 7 is a new HP Pavilion G7 laptop. I was confused over the differences in the appearance of Firefox on both since they are both v4.o. I was able to download my bookmarks to a .json file from my XP c
-
ITunes video playback quality is not that smooth
Hello: Two questions-- 1. Why do the music videos I purchase on iTunes (and then play on iTunes) freeze up for a few seconds after I push play, but then otherwise playback is OK? 2. Why does the "spinning beachball" appear almost everytime I press pl
-
Hi all, If customer has paid his balance entirely then we want to send him a letter saying that his balance is zero $ .Is their any standard SAP report for this or we will hav to custome it . Thanks Nik
-
Can I make a custom calendar in Pages using an iCal or .ics file?
And if so, how would I do it?