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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Build a Query in MuleSoft With Optional Parameters
  • MuleSoft: Connect PostgreSQL Database and Call PostgreSQL Function
  • Connecting Snowflake With MuleSoft Database Connector
  • MuleSoft OAuth 2.0 Provider: Password Grant Type

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  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.

By 
Surya Satya Kumar Uppuluri user avatar
Surya Satya Kumar Uppuluri
·
Mar. 14, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
10.0K 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.

Related

  • Build a Query in MuleSoft With Optional Parameters
  • MuleSoft: Connect PostgreSQL Database and Call PostgreSQL Function
  • Connecting Snowflake With MuleSoft Database Connector
  • MuleSoft OAuth 2.0 Provider: Password Grant Type

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!