1

I have created a logger in my main class as:

public static Logger logger = Logger.getLogger( MainClass.class.getName());

I declared it public static.

this is log4j.properties:

Root logger option

log4j.rootLogger=INFO, file

Direct log messages to a log file

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\loging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Now i want to access this logger object in different class. When i tried giving logger directly it is giving error though i made it public static.

Below is my class from which i am trying to access logger object:

public class Db_Connector 
{
     MainClass.logger <------error
     //create ResultSet Class Object
     public ResultSet GetDataFromDB(){

        ResultSet resultset = null;
         try {  

                DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());   
                System.out.println("Connecting to the database...");   
                Connection connection = DriverManager.getConnection(
                        "jdbc:oracle:thin:@host:1521:Db", "User","pass01");
                Statement statement = connection.createStatement();   
                resultset = statement.executeQuery("select * from employee"); 

            } 
         catch (Exception e) {   
                System.out.println("The exception raised is:" + e);   
                            } 

         return resultset;
        }   
}
Aquarius24
  • 1,806
  • 6
  • 33
  • 61
  • 1
    What error do you have, and how are you trying to access the logger? – Erik Pragt Jun 18 '13 at 06:15
  • In another class i am trying MainClass.logger – Aquarius24 Jun 18 '13 at 06:23
  • What's the Exception when you call MainClass.logger - it's almost impossible to help otherwise. – Jim Jun 18 '13 at 06:31
  • May I ask, why you want to share your logger instance between the classes? Typically you create one instance per class, so usually there is no need to share it. Discussed here for example [here](http://stackoverflow.com/questions/1770076/log4j-strategies-for-creating-logger-instances). – crusam Jun 18 '13 at 07:05

2 Answers2

1

Make sure that the Class that wraps up your Logger is also public

sameh.q
  • 1,691
  • 2
  • 23
  • 48
  • Would you please provide code section of where you are trying to access your logger – sameh.q Jun 18 '13 at 06:30
  • 1
    You can't call `MainClass.logger` in that location where you mark it as error you should be able to access it normally inside a method `MainClass.Logger.something()...` ie: inside `GetDataFromDB()` – sameh.q Jun 18 '13 at 06:54
0

You should create public static variable in your DB_Connector class and assign MainClass.logger to it.