KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Log4JTest


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 /**
17 // Class JDBCAppender, writes messages into a database
18
19 // The JDBCAppender is configurable at runtime in two alternatives :
20 // 1. Configuration-file
21 // Define the options in a file and call a PropertyConfigurator.configure(file)-method.
22 // 2. method JDBCAppender::setOption(JDBCAppender.xxx_OPTION, String value)
23
24 // The sequence of some options is important :
25 // 1. Connector-option OR/AND Database-options
26 // Any database connection is required !
27 // 2. (Table-option AND Columns-option) OR SQL-option
28 // Any statement is required !
29 // 3. All other options can be set at any time...
30 // The other options are optional and have a default initialization, which can be custumized.
31
32 // All available options are defined as static String-constants in JDBCAppender named xxx_OPTION.
33
34 // Here is a description of all available options :
35 // 1. Database-options to connect to the database
36 // - URL_OPTION : a database url of the form jdbc:subprotocol:subname
37 // - USERNAME_OPTION : the database user on whose behalf the connection is being made
38 // - PASSWORD_OPTION : the user's password
39 //
40 // 2. Connector-option to specify your own JDBCConnectionHandler
41 // - CONNECTOR_OPTION : a classname which is implementing the JDBCConnectionHandler-interface
42 // This interface is used to get a customized connection.
43 // If in addition the database-options are given, these options will be used
44 // for invocation of the JDBCConnectionHandler-interface to get a connection.
45 // Else if no database-options are given, the JDBCConnectionHandler-interface is called without these options.
46 //
47 // 3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event
48 // - SQL_OPTION : a sql-statement which will be used to write to the database
49 // If you give this option, the table-option and columns-option will be ignored !
50 // Use the variable @MSG@ on that location in the statement, which has to be dynamically replaced by the message.
51 //
52 // 4. Table-option to specify one table contained by the database
53 // - TABLE_OPTION : the table in which the logging will be done
54 //
55 // 5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!)
56 // - COLUMNS_OPTION : a formatted list of column-descriptions
57 // Each column description consists of
58 // - the name of the column (required)
59 // - a logtype which is a static constant of class LogType (required)
60 // - and a value which depends by the LogType (optional/required, depending by logtype)
61 // Here is a description of the available logtypes of class LogType :
62 // o MSG = a value will be ignored, the column will get the message. (One columns need to be of this type!)
63 // o STATIC = the value will be filled into the column with every logged message. (Ensure that the type of value can be casted into the sql-type of the column!)
64 // o ID = value must be a classname, which implements the JDBCIDHandler-interface.
65 // o TIMESTAMP = a value will be ignored, the column will be filled with a actually timestamp with every logged message.
66 // o EMPTY = a value will be ignored, the column will be ignored when writing to the database (Ensure to fill not nullable columns by a database trigger!)
67 // If there are more than one column to describe, the columns must be separated by a TAB-delimiter (' ') !
68 // The arguments of a column-description must be separated by the delimiter '~' !
69 // (Example : name1~logtype1~value1 name2~logtype2~value2...)
70 //
71 // 6. Layout-options to define the layout of the messages (optional)
72 // - the layout wont be set by a xxx_OPTION
73 // Configuration-file : see at the following configuration-file example
74 // JDBCAppender::setOption() : see at the following code example
75 // The default is a layout of class org.apache.log4j.PatternLayout with ConversionPattern=%m
76 //
77 // 7. Buffer-option to define the size of the message-event-buffer (optional)
78 // - BUFFER_OPTION : define how many messages will be buffered until they will be updated to the database.
79 // The default is a update on every message (buffer=1=no buffer).
80 //
81 // 8. Commit-option to define a auto-commitment
82 // - COMMIT_OPTION : define whether updated messages should be committed to the database (Y) or not (N).
83 // The default is a commit on every buffer-flush.
84
85
86 // Here is a Configuration-file example, which can be used with the PropertyConfigurator :
87 //
88 // Declare a appender variable named JDBC
89 log4j.rootCategory=JDBC
90
91 // JDBC is a class of JDBCAppender, which writes messages into a database
92 log4j.appender.JDBC=JDBCAppender
93
94 // 1. Database-options to connect to the database
95 log4j.appender.JDBC.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))
96 log4j.appender.JDBC.username=mex_pr_dev60
97 log4j.appender.JDBC.password=mex_pr_dev60
98
99 // 2. Connector-option to specify your own JDBCConnectionHandler
100 log4j.appender.JDBC.connector=MyConnectionHandler
101
102 // 3. SQL-option to specify a static sql-statement which will be performed with every occuring message-event
103 log4j.appender.JDBC.sql=INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me')
104
105 // 4. Table-option to specify one table contained by the database
106 log4j.appender.JDBC.table=logtest
107
108 // 5. Columns-option to describe the important columns of the table (Not nullable columns are mandatory to describe!)
109 log4j.appender.JDBC.columns=id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~Thomas Fenner (t.fenner@klopotek.de)
110
111 // 6. Layout-options to define the layout of the messages (optional)
112 log4j.appender.JDBC.layout=org.apache.log4j.PatternLayout
113 log4j.appender.JDBC.layout.ConversionPattern=%m
114
115 // 7. Buffer-option to define the size of the message-event-buffer (optional)
116 log4j.appender.JDBC.buffer=1
117
118 // 8. Commit-option to define a auto-commitment
119 log4j.appender.JDBC.commit=Y
120 */

121
122 // Here is a code example to configure the JDBCAppender with a configuration-file :
123

124 import org.apache.log4j.*;
125 import java.sql.*;
126 import java.lang.*;
127 import java.util.*;
128
129 public class Log4JTest
130 {
131     // Create a category instance for this class
132
static Category cat = Category.getInstance(Log4JTest.class.getName());
133
134    public static void main(String JavaDoc[] args)
135    {
136       // Ensure to have all necessary drivers installed !
137
try
138       {
139             Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
140             DriverManager.registerDriver(d);
141         }
142       catch(Exception JavaDoc e){}
143
144       // Set the priority which messages have to be logged
145
cat.setPriority(Priority.INFO);
146
147         // Configuration with configuration-file
148
PropertyConfigurator.configure("log4jtestprops.txt");
149
150       // These messages with Priority >= setted priority will be logged to the database.
151
cat.debug("debug"); //this not, because Priority DEBUG is less than INFO
152
cat.info("info");
153       cat.error("error");
154       cat.fatal("fatal");
155    }
156 }
157
158 // Here is a code example to configure the JDBCAppender without a configuration-file :
159
/*
160 import org.apache.log4j.*;
161 import java.sql.*;
162 import java.lang.*;
163 import java.util.*;
164
165 public class Log4JTest
166 {
167     // Create a category instance for this class
168    static Category cat = Category.getInstance(Log4JTest.class.getName());
169
170    public static void main(String[] args)
171    {
172     // A JDBCIDHandler
173        MyIDHandler idhandler = new MyIDHandler();
174
175       // Ensure to have all necessary drivers installed !
176     try
177       {
178             Driver d = (Driver)(Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
179             DriverManager.registerDriver(d);
180         }
181       catch(Exception e){}
182
183       // Set the priority which messages have to be logged
184         cat.setPriority(Priority.DEBUG);
185
186       // Create a new instance of JDBCAppender
187       JDBCAppender ja = new JDBCAppender();
188
189       // Set options with method setOption()
190       ja.setOption(JDBCAppender.CONNECTOR_OPTION, "MyConnectionHandler");
191       ja.setOption(JDBCAppender.URL_OPTION, "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))");
192       ja.setOption(JDBCAppender.USERNAME_OPTION, "mex_pr_dev60");
193       ja.setOption(JDBCAppender.PASSWORD_OPTION, "mex_pr_dev60");
194
195         ja.setOption(JDBCAppender.TABLE_OPTION, "logtest");
196
197       // There are two ways to setup the column-descriptions :
198       // 1. Use the the method setOption(JDBCAppender.COLUMNS_OPTION, column-description)
199         //ja.setOption(JDBCAppender.COLUMNS_OPTION, "id_seq~EMPTY id~ID~MyIDHandler msg~MSG created_on~TIMESTAMP created_by~STATIC~:-) Thomas Fenner (t.fenner@klopotek.de)");
200         // 2. Use the better way of coding with method setLogType(String columnname, int LogType.xxx, Object xxx)
201         ja.setLogType("id_seq", LogType.EMPTY, "");
202         ja.setLogType("id", LogType.ID, idhandler);
203         ja.setLogType("msg", LogType.MSG, "");
204         ja.setLogType("created_on", LogType.TIMESTAMP, "");
205         ja.setLogType("created_by", LogType.STATIC, "FEN");
206
207       // If you just want to perform a static sql-statement, forget about the table- and columns-options,
208       // and use this one :
209         //ja.setOption(JDBCAppender.SQL_OPTION, "INSERT INTO LOGTEST (id, msg, created_on, created_by) VALUES (1, @MSG@, sysdate, 'me')");
210
211       // other options
212         //ja.setOption(JDBCAppender.BUFFER_OPTION, "1");
213         //ja.setOption(JDBCAppender.COMMIT_OPTION, "Y");
214
215       // Define a layout
216         //ja.setLayout(new PatternLayout("%m"));
217
218       // Add the appender to a category
219       cat.addAppender(ja);
220
221       // These messages with Priority >= setted priority will be logged to the database.
222         cat.debug("debug");
223       cat.info("info");
224       cat.error("error");
225       cat.fatal("fatal");
226     }
227 }
228 */

229
230 // Implement a sample JDBCConnectionHandler
231
class MyConnectionHandler implements JDBCConnectionHandler
232 {
233     Connection con = null;
234    //Default connection
235
String JavaDoc url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1521))(ADDRESS=(COMMUNITY=tcp.world)(PROTOCOL=TCP)(Host=LENZI)(Port=1526)))(CONNECT_DATA=(SID=LENZI)))";
236    String JavaDoc username = "mex_pr_dev60";
237    String JavaDoc password = "mex_pr_dev60";
238
239    public Connection getConnection()
240    {
241     return getConnection(url, username, password);
242    }
243
244    public Connection getConnection(String JavaDoc _url, String JavaDoc _username, String JavaDoc _password)
245    {
246     try
247       {
248         if(con != null && !con.isClosed()) con.close();
249             con = DriverManager.getConnection(_url, _username, _password);
250             con.setAutoCommit(false);
251       }
252       catch(Exception JavaDoc e){}
253
254     return con;
255    }
256 }
257
258
259 // Implement a sample JDBCIDHandler
260
class MyIDHandler implements JDBCIDHandler
261 {
262     private static long id = 0;
263
264     public synchronized Object JavaDoc getID()
265    {
266         return new Long JavaDoc(++id);
267    }
268 }
269
270
271
Popular Tags