<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
    <channel>
        <title>Tutorial :: Store Java Logs to Database Using log4j</title>
        <link>http://www.cubrid.org/?mid=store_java_logs_to_databdase_using_log4j</link>
        <description>Tutorial :: Store Java Logs to Database Using log4j</description>
        <language>en</language>
        <pubDate>Wed, 22 Dec 2010 08:52:23 -0800</pubDate>
        <lastBuildDate>Wed, 22 Jun 2011 09:17:11 -0800</lastBuildDate>
        <generator>XpressEngine 1.4.4.1</generator>
                        										        <item>
            <title>Tutorial :: Store Java Logs to Database Using log4j</title>
            <dc:creator>admin</dc:creator>
            <link>http://www.cubrid.org/store_java_logs_to_databdase_using_log4j</link>
            <guid isPermaLink="true">http://www.cubrid.org/store_java_logs_to_databdase_using_log4j</guid>
                                    <description><![CDATA[<h1>Store Java Logs to Database Using log4j</h1>
<div class="category"><a href="/analyzing_jdbc_logs">⇐Analyzing JDBC Logs with log4jdbc</a></div>

<p><a href="http://logging.apache.org/log4j/1.2/" target="_blank">log4j</a>&nbsp;is one of the most powerful and commonly used logging system used when programming in Java. There are many different ways how you can utilize it in your project.&nbsp;One of the features of log4j framework is to store Java log messages to a JDBC-enabled database. Here we will show how to store the logs into CUBRID Database. Since CUBRID provides the JDBC interface, configuration log4j is pretty straightforward.</p>

<div class="contents-table">
<h3>Table of Contents</h3>

<ul>
    <li><a class="toTop">Back to Top</a></li>
    <li><a href="#downloads">Downloads</a></li>
    <li><a href="#example">Example</a></li>
    <li><a href="#configure">Configure log4j</a></li>
    <li><a href="#see-also">See also</a></li>
    <li><a href="#getting-help">Getting Help</a></li>
</ul>
</div>

<h2 id="downloads">Downloads</h2>

<ul>
<li><b>CUBRID 1.1 or higher<br /></b><a href="/downloads" target="_self">Download</a> the latest version of CUBRID Database, and follow the <a href="/tutorials#getting-started" target="_self">installation instructions</a>.</li><li><b>Java Development Kit<br /></b>Download the latest JDK from&nbsp;<a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">http://www.oracle.com/technetwork/java/javase/downloads/index.html</a>.</li><li><b>log4j<br /></b>Download log4j from <a href="http://logging.apache.org/log4j/1.2/download.html">http://logging.apache.org/log4j/1.2/download.html</a>.</li>
</ul>

<h2 id="example">Example</h2>

<p>Before we get into configurations, let's create a sample code in Java.</p>

<ul>
<li>Create a new directory where for this example.</li><li>Copy two libraries to this directory:</li><ol><li><b>log4j-1.2.16.jar</b> ? This is the main <b>log4j</b>&nbsp;library.&nbsp;You can find it inside the <b>log4j</b> archive you have downloaded above.</li><li><b>cubrid_jdbc.jar</b> ? This is the main CUBRID JDBC driver. You can find it in the <b>/jdbc</b> directory which is located inside the main directory where you have installed CUBRID.</li></ol><li>Now let's create a simple Java class that does some logging. Open your editor and create a new file called <b>Tutorial.java</b>.
</li>
<div class="code">
<div editor_component="code_highlighter" code_type="java" first_line="1" collapse="false" nogutter="false" nocontrols="false">
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;

public class Tutorial {
    public static void main( String[] args ) {
        Logger log = LogManager.getLogger(Tutorial.class);
        log.info("Application successfully initialized");
        log.warn("Application is about to finish");
        try {
            if ( 1 / 0 == 0 ) {
                System.out.println("Fry the FPU");
            }
        } catch( Exception ex) {
            log.error("Some exception has been thrown", ex);
        }
        log.fatal("Application has finished");
    }
}
</div>
</div>
</ul>

<h2 id="configure">Configure log4j</h2>

<p>In order to enable log4j we will have to create a configuration file. In this configuration we will define three appenders: Console, File and JDBC. This way, the messages will be written to all these appenders. Open text editor and put the following configuration (<i>note that CUBRID JDBC specific code is written in bold</i>). Save as <b>log4j.properties</b> in the same directory with Java file.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="java" first_line="1" collapse="false" nogutter="false" nocontrols="false">
log4j.rootCategory=DEBUG, Console, File, CUBRID

# Console appender
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n

# File
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.file=tutorial.log
log4j.appender.File.MaxFileSize=100KB
log4j.appender.File.layout=org.apache.log4j.PatternLayout

# CUBRID Database
log4j.appender.CUBRID = org.apache.log4j.jdbc.JDBCAppender
log4j.appender.CUBRID.driver = cubrid.jdbc.driver.CUBRIDDriver
log4j.appender.CUBRID.user = dba
log4j.appender.CUBRID.password =
log4j.appender.CUBRID.URL = jdbc:cubrid:localhost:30000:demodb:public::
log4j.appender.CUBRID.sql = INSERT INTO LOGS VALUES('%x','%d{yyyy-MM-dd  HH:mm:ss.SSS}','%C','%p','%m')
log4j.appender.CUBRID.layout=org.apache.log4j.PatternLayout
</div>
</div>

<p>As you can see, configuring the JDBC appender requires specifying <b>JDBC URL</b> and also the <b>connection credentials</b>. Additionally we have set the <b>format of the timestamp</b> into <i>log4j.appender.CUBRID.sql</i> in order to create a database compatible DATETIME value.</p>

<p>Next, before we can use the JDBC logging with CUBRID we will have to <b>create a new table to store the logs</b>. By default, CUBRID comes with a <i>sample database</i> named <b>demodb</b> accessible to <b>dba</b> user with an empty password. We will use this database to store our table for logging. Open up the command line terminal and execute the following SQL statement using csql utility to create our table. You can, in fact, achieve the same results if you use the <a href="/cubrid_manager">CUBRID Manager</a>, CUBRID's main GUI-based database administration tool.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="bash" first_line="1" collapse="false" nogutter="false" nocontrols="false">
csql -u dba -c 'CREATE TABLE logs (user_id VARCHAR(20) NOT NULL, dated DATETIME NOT NULL, logger VARCHAR(50) NOT NULL, "level" VARCHAR(10) NOT NULL, message VARCHAR(1000) NOT NULL);' demodb
</div>
</div>

<p>Now <b>compile your Java source code</b> into Java .class with the following command. This will output the Tutorial.class file.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="java" first_line="1" collapse="false" nogutter="false" nocontrols="false">
javac -cp log4j-1.2.16.jar Tutorial.java
</div>
</div>

<p>Then run the Tutorial.class.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="java" first_line="1" collapse="false" nogutter="false" nocontrols="false">
java -cp .:log4j-1.2.16.jar:cubrid_jdbc.jar Tutorial
</div>
</div>

<p>You will see the following output.</p>

<p><img src="http://www.cubrid.org/files/attach/images/49/821/003/log4j-java-class-output.png" alt="log4j-java-class-output.png" width="725" height="109" editor_component="image_link"/></p>

<p>Let's look into our CUBRID Database Table. With <b>csql</b> utility select all records from our table.</p>

<div class="code">
<div editor_component="code_highlighter" code_type="java" first_line="1" collapse="false" nogutter="false" nocontrols="false">
csql -u dba -c "SELECT * FROM logs" demodb
</div>
</div>

<p>You will see the following results.</p>

<p><img src="http://www.cubrid.org/files/attach/images/49/821/003/log4j-log-select.png" alt="log4j-log-select.png" width="725" height="160" editor_component="image_link"/></p>

<p>Setting up log4j with CUBRID is very simple and straightforward as you can see. However, log4j by itself has one drawback - it does not log Java exceptions into the JDBC appender. If you navigate to log4j website, it states: <i>"WARNING: This version of JDBCAppender is very likely to be completely replaced in the future. Moreoever, it does not log exceptions."</i> So, we recommend you to consult the documentation before you decide to use the JDBC appender with any database.</p>


<h2 id="see-also">See also</h2>

<ul>
<li>log4j home page&nbsp;<a href="http://logging.apache.org/log4j/1.2/" target="_blank">http://logging.apache.org/log4j/1.2/</a></li><li>log4jdbc home page <a href="http://code.google.com/p/log4jdbc/" target="_blank">http://code.google.com/p/log4jdbc/</a></li><li>SLF4J manual&nbsp;<a href="http://www.slf4j.org/manual.html">http://www.slf4j.org/manual.html</a></li><li>log4j manual&nbsp;<a href="http://logging.apache.org/log4j/1.2/manual.html">http://logging.apache.org/log4j/1.2/manual.html</a></li><li><a href="http://books.google.com/books?id=hZBimlxiyAcC&amp;printsec=frontcover&amp;dq=log4j&amp;source=bl&amp;ots=QeQj3Y2_U9&amp;sig=4NY5iYTpBp1ok85oTTqMbRXk3mY&amp;hl=en&amp;ei=354RTebiEYO8vQOh0tSDDg&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=8&amp;ved=0CGQQ6AEwBw#v=onepage&amp;q&amp;f=false" target="_blank">THE COMPLETE LOG4J MANUAL</a> - Google Books</li></ul>

<h2 id="getting-help">Getting Help</h2>

<p>If you have any difficulties with log4j, post your question to CUBRID Forum at&nbsp;<a href="/?mid=forum&amp;category=195533">http://www.cubrid.org/?mid=forum&amp;category=195533</a>.</p>]]></description>
                        <pubDate>Wed, 22 Dec 2010 07:53:09 -0800</pubDate>
                        <category>java</category>
                        <category>log4j</category>
                        <category>jdbc</category>
                                </item>
            </channel>
</rss>
