DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. Logging to Database Using Log4J in MuleSoft

Logging to Database Using Log4J in MuleSoft

By making some changes, appending some properties to log4j.xml, and using custom Java code to connect to the database, we can make logging to a database possible.

Surya Satya Kumar Uppuluri user avatar by
Surya Satya Kumar Uppuluri
·
Mar. 14, 17 · Tutorial
Like (2)
Save
Tweet
Share
8.37K Views

Join the DZone community and get the full member experience.

Join For Free

Though Mule does logging to a file on the server, sometimes, there arises a need to maintain a log database. This makes the process of debugging easy with the ability to query a log. Mule uses Log4J for its logging. So, by making the necessary changes, appending some properties to log4j.xml, and using custom Java code to connect to the database, we can make logging to a database possible.

This is how to do it.

1. Build a Mule Flow

I have made a simple flow that reads a file from one location and writes to another location.

Mule Flow



2. Make a Database Connection Using Java

package com.surya.logging;
import java.sql.Connection; 
import java.sql.SQLException; 
import java.util.Properties; 
import javax.sql.DataSource; 
import org.apache.commons.dbcp.DriverManagerConnectionFactory; 
import org.apache.commons.dbcp.PoolableConnection; 
import org.apache.commons.dbcp.PoolableConnectionFactory; 
import org.apache.commons.dbcp.PoolingDataSource; 
import org.apache.commons.pool.impl.GenericObjectPool;  
publicclass LoggingConnectionFactory {    
 privatestaticinterface Singleton {        
  final LoggingConnectionFactory INSTANCE = new LoggingConnectionFactory();    
 }     
 privatefinal DataSource dataSource;    
 private LoggingConnectionFactory() {

          
  GenericObjectPool < PoolableConnection > pool = new GenericObjectPool < PoolableConnection > ();        
  DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:oracle:thin:@localhost:1521:XE", "your_db_username", "your_db_password");        
  new PoolableConnectionFactory(connectionFactory, pool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED);         
  this.dataSource = new PoolingDataSource(pool);    
 }     
 publicstatic Connection getDatabaseConnection() throws SQLException {        
  return Singleton.INSTANCE.dataSource.getConnection();    
 }
}

The above code returns a connection by using a data source. We pass the URL for the connection, username, and password of the database as parameters to DriverManagerConnectionFactory.

3. Create a Table With Required Parameters as Columns

The required values for logging would be:

  • Date and time of logging.
  • Level of logging.
  • Logger class.
  • Message that is to be logged.
  • Exception (if any).

The SQL query to create such a table is as follows:

CREATE TABLE logentry2 
  ( 
     eventdate     DATE NULL, 
     literalcolumn VARCHAR(500) NULL, 
     loglevel      VARCHAR(500) NULL, 
     logger        VARCHAR(500) NULL, 
     message       VARCHAR(4000) NULL, 
     exception     VARCHAR(500) NULL 
  ); 

4. Customize log4j.xml 

Now, we have to add the table name, column names, Java class, and methods used into the log4j.xml file.

It is as follows:

<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Appenders>
<RollingFile name="file" fileName="D:/CustomLogs${sys:file.separator}logs${sys:file.separator}flow_control.log"#
                       filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}flow_control-%i.log">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n" />
<SizeBasedTriggeringPolicy size="10 MB" />
<DefaultRolloverStrategy max="10"/>
</RollingFile>
<RollingFile name="file" fileName="D:/MuleLogs${sys:file.separator}logs${sys:file.separator}flow_control.log"
          filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}flow_control-%i.log">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n" />
<SizeBasedTriggeringPolicy size="10 MB" />
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Appenders>
<JDBC name="databaseAppender" tableName="sys.LogEntry2" ignoreExceptions="true" > #
  
<ConnectionFactory class="com.surya.logging.LoggingConnectionFactory" method="getDatabaseConnection" /> #
  
<Column name="eventDate" isEventTimestamp="true" /> #
  
<Column name="literalColumn" literal="" /> #
  
<Column name="loglevel" pattern="%level" /> #
  
<Column name="logger" pattern="%logger" /> #
  
<Column name="message" pattern="%message"  /> #
  
<Column name="exception" pattern="%ex{full}" /> #

</JDBC> #
    
</Appenders> #
    
<Loggers>
<!-- CXF is used heavily by Mule for web services -->
<AsyncLogger name="org.apache.cxf" level="WARN"/>
<!-- Apache Commons tend to make a lot of noise which can clutter the log-->
<AsyncLogger name="org.apache" level="WARN"/>
<!-- Reduce startup noise -->
<AsyncLogger name="org.springframework.beans.factory" level="WARN"/>
<!-- Mule classes -->
<AsyncLogger name="org.mule" level="INFO"/>
<AsyncLogger name="com.mulesoft" level="INFO"/>
<!-- Reduce DM verbosity -->
<AsyncLogger name="org.jetel" level="WARN"/>
<AsyncLogger name="Tracking" level="WARN"/>
<AsyncRoot level="INFO">
<AppenderRef ref="file" />
</AsyncRoot>
<Root level="INFO"> #
            
<AppenderRef ref="databaseAppender" /> #
        
</Root> #
    
</Loggers>
</Configuration>

The properties followed by a # are the changes you have to make in your log4j.xml file.

5. Test

Now, run your Mule application and check the database for logs.

Database Logs


And you're done!


Database connection Log4j MuleSoft

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed Stateful Edge Platforms
  • Best Practices for Writing Clean and Maintainable Code
  • The Enterprise, the Database, the Problem, and the Solution
  • 5 Tips for Optimizing Your React App’s Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: