{{announcement.body}}
{{announcement.title}}

Enable Custom Logging For MuleSoft Application Using Log4J2 Splunk HTTP and HTTP Appender

DZone 's Guide to

Enable Custom Logging For MuleSoft Application Using Log4J2 Splunk HTTP and HTTP Appender

Logging is an important part of your environment for visualizing the data, troubleshooting, debugging and identifying the production issues quickly.

· Cloud Zone ·
Free Resource

Introduction

Logging is a very important part of your environment for visualizing the data, troubleshooting, debugging and identifying the production issues quickly.

Logging must be robust, consistent and reliable and most importantly that we can have some centralized and easy to use tools that can be used for logging purposes. There are various logging tools like Splunk, ELK, etc.

MuleSoft provides its logging framework for storing applications and system logs. The main reason for using a custom logging framework is that MuleSoft in Cloudhub stores data for 30 days or up to 100 MB. 

Once the application is deleted, we will lose all the logs. So we required logging tools like Splunk for storing data and can persist for a longer time.

Splunk logging tool can be used to enable log MuleSoft On-Premise Runtime logs, On-Premise MuleSoft Application and CloudHub Application logs.

In the last article, we have seen how to set up Splunk and enable logging for MuleSoft Application. Click here for more details.

Enable Logging For CloudHub Application

Before enabling the logging for Cloudhub application, you need Disable CloudHub logs. By default, this option is not available and you need to raise a ticket with MuleSoft for providing this option. 

cloudhub

Once you disabled CloudHub logs, MuleSoft is not responsible for below things

  • MuleSoft is not responsible for lost logging data due to the misconfiguration of your log4j appender.
  • MuleSoft is also not responsible for misconfigurations that result in performance degradation, running out of disk space, or other side effects.
  • When you disable the default CloudHub application logs, then only the system logs are available. For application worker logs, please check your own application’s logging system. Downloading logs is not an option in this scenario.
  • Only Asynchronous log appenders can be used, Synchronous appenders should not be used.
  • Use asynchronous loggers and not synchronous ones is to avoid threading issues. Synchronous loggers can lock threads waiting for responses.

You need to create log4j2.xml at location src/main/resources.

log4j2.xml

There are two ways you can send logs to Splunk 

  • HTTP Appender 
  • Splunk HTTP

We will see how we can send logs from CloudHub application to Splunk using Splunk HTTP.

You will be requiring the token and connection details related to Splunk. So you can go through the article and understand how to fetch those details.

You need to add a SplunkHttp appender in log4j.xml. Provide URL to connect Splunk, source, pattern layout, etc.

XML
 




xxxxxxxxxx
1


 
1
<SplunkHttp name="SPLUNK-CLOUD" source="mule-cloudhub-app"
2
            url="http://localhost:8088/" 
3
            token="b3a34eabd-b5f4-471431-97d2-e5b234af5bae9e" index="main"
4
            disableCertificateValidation="true">
5
            <PatternLayout pattern="[%d{MM-dd HH:mm:ss}] %-5p %c{1} [%t]: %m%n" />
6
</SplunkHttp>



You need to make sure the logger must be asynchronous and it is recommended by MuleSoft also.

While using SplunkHttp, you need to add the following dependency in pom.xml of your application.

XML
 




xxxxxxxxxx
1


1
<dependency>
2
    <groupId>com.splunk.logging</groupId>
3
    <artifactId>splunk-library-javalogging</artifactId>
4
    <version>1.7.3</version>
5
</dependency>



You may require to add below two additional dependencies.

XML
 




xxxxxxxxxx
1
11


1
<dependency>
2
    <groupId>org.apache.logging.log4j</groupId>
3
    <artifactId>log4j-core</artifactId>
4
    <version>2.10.0</version>
5
</dependency>
6
<dependency>
7
    <groupId>org.apache.logging.log4j</groupId>
8
    <artifactId>log4j-api</artifactId>
9
    <version>2.10.0</version>
10
</dependency>



You will be also required to add a repository into your pom.xml of your application.

XML
 




xxxxxxxxxx
1


 
1
<repository>
2
    <id>splunk-artifactory</id>
3
    <name>Splunk Releases</name>
4
    <url>http://splunk.jfrog.io/splunk/ext-releases-local</url>
5
</repository>



You can add more loggers like Log4J2CloudhubLogAppender into your log4j2.xml to enable logging on the CloudHub log console of your application.

XML
 




xxxxxxxxxx
1
18


 
1
<Log4J2CloudhubLogAppender name="CLOUDHUB"
2
            addressProvider="com.mulesoft.ch.logging.DefaultAggregatorAddressProvider"
3
            applicationContext="com.mulesoft.ch.logging.DefaultApplicationContext"
4
            appendRetryIntervalMs="${sys:logging.appendRetryInterval}"
5
            appendMaxAttempts="${sys:logging.appendMaxAttempts}"
6
            batchSendIntervalMs="${sys:logging.batchSendInterval}"
7
            batchMaxRecords="${sys:logging.batchMaxRecords}" memBufferMaxSize="${sys:logging.memBufferMaxSize}"
8
            journalMaxWriteBatchSize="${sys:logging.journalMaxBatchSize}"
9
            journalMaxFileSize="${sys:logging.journalMaxFileSize}"
10
            clientMaxPacketSize="${sys:logging.clientMaxPacketSize}"
11
            clientConnectTimeoutMs="${sys:logging.clientConnectTimeout}"
12
            clientSocketTimeoutMs="${sys:logging.clientSocketTimeout}"
13
            serverAddressPollIntervalMs="${sys:logging.serverAddressPollInterval}"
14
            serverHeartbeatSendIntervalMs="${sys:logging.serverHeartbeatSendIntervalMs}"
15
            statisticsPrintIntervalMs="${sys:logging.statisticsPrintIntervalMs}">
16
            <PatternLayout pattern="[%d{MM-dd HH:mm:ss}] %-5p %c{1} [%t]: %m%n" />
17
</Log4J2CloudhubLogAppender>
18
 
          



Below is full log4j2.xml which can be used for your application for enabling custom logging on CloudHub and Splunk.

XML
 




x



1
2
<?xml version="1.0" encoding="UTF-8"?>
3
<Configuration status="INFO" name="cloudhub"
4
    packages="com.mulesoft.ch.logging.appender,com.splunk.logging,org.apache.logging.log4j">
5
    <Appenders>
6
        <Log4J2CloudhubLogAppender name="CLOUDHUB"
7
            addressProvider="com.mulesoft.ch.logging.DefaultAggregatorAddressProvider"
8
            applicationContext="com.mulesoft.ch.logging.DefaultApplicationContext"
9
            appendRetryIntervalMs="${sys:logging.appendRetryInterval}"
10
            appendMaxAttempts="${sys:logging.appendMaxAttempts}"
11
            batchSendIntervalMs="${sys:logging.batchSendInterval}"
12
            batchMaxRecords="${sys:logging.batchMaxRecords}" memBufferMaxSize="${sys:logging.memBufferMaxSize}"
13
            journalMaxWriteBatchSize="${sys:logging.journalMaxBatchSize}"
14
            journalMaxFileSize="${sys:logging.journalMaxFileSize}"
15
            clientMaxPacketSize="${sys:logging.clientMaxPacketSize}"
16
            clientConnectTimeoutMs="${sys:logging.clientConnectTimeout}"
17
            clientSocketTimeoutMs="${sys:logging.clientSocketTimeout}"
18
            serverAddressPollIntervalMs="${sys:logging.serverAddressPollInterval}"
19
            serverHeartbeatSendIntervalMs="${sys:logging.serverHeartbeatSendIntervalMs}"
20
            statisticsPrintIntervalMs="${sys:logging.statisticsPrintIntervalMs}">
21
            <PatternLayout pattern="[%d{MM-dd HH:mm:ss}] %-5p %c{1} [%t]: %m%n" ></PatternLayout>
22
        </Log4J2CloudhubLogAppender>
23
        <SplunkHttp name="SPLUNK-CLOUD" source="mule-cloudhub-app"
24
            url="http://localhost:8088/" 
25
            token="b3a34eabd-b5f4-471431-97d2-e5b234af5bae9e" index="main"
26
            disableCertificateValidation="true">
27
            <PatternLayout pattern="[%d{MM-dd HH:mm:ss}] %-5p %c{1} [%t]: %m%n" ></PatternLayout>
28
        </SplunkHttp>
29
    </Appenders>
30
    <Loggers>
31
        <AsyncLogger
32
            name="org.mule.runtime.core.internal.processor.LoggerMessageProcessor"
33
            level="INFO" ></AsyncLogger>
34
        <AsyncLogger name="com.mulesoft.agent" level="INFO" ></AsyncLogger>
35
        <AsyncRoot level="INFO">
36
            <AppenderRef ref="SPLUNK-CLOUD" ></AppenderRef>
37
            <AppenderRef ref="CLOUDHUB" ></AppenderRef>
38
        </AsyncRoot>
39
        <AsyncLogger name="com.gigaspaces" level="ERROR" ></AsyncLogger>
40
        <AsyncLogger name="com.j_spaces" level="ERROR" ></AsyncLogger>
41
        <AsyncLogger name="com.sun.jini" level="ERROR" ></AsyncLogger>
42
        <AsyncLogger name="net.jini" level="ERROR" ></AsyncLogger>
43
        <AsyncLogger name="org.apache" level="WARN" ></AsyncLogger>
44
        <AsyncLogger name="org.apache.cxf" level="WARN" ></AsyncLogger>
45
        <AsyncLogger name="org.springframework.beans.factory"
46
            level="WARN" ></AsyncLogger>
47
        <AsyncLogger name="org.mule" level="INFO" ></AsyncLogger>
48
        <AsyncLogger name="com.mulesoft" level="INFO" ></AsyncLogger>
49
        <AsyncLogger name="org.jetel" level="WARN" ></AsyncLogger>
50
        <AsyncLogger name="Tracking" level="WARN" ></AsyncLogger>
51
        <AsyncLogger name="org.mule" level="INFO" ></AsyncLogger>
52
        <AsyncLogger name="com.mulesoft" level="INFO" ></AsyncLogger>
53
        <AsyncLogger name="org.mule.extensions.jms" level="INFO" ></AsyncLogger>
54
        <AsyncLogger name="org.mule.service.http.impl.service.HttpMessageLogger"
55
            level="INFO" ></AsyncLogger>
56
        <AsyncLogger name="org.mule.extension.salesforce" level="INFO" ></AsyncLogger>
57
        <AsyncLogger name="org.mule.extension.ftp" level="INFO" ></AsyncLogger>
58
        <AsyncLogger name="org.mule.extension.sftp" level="INFO" ></AsyncLogger>
59
        <AsyncLogger name="com.mulesoft.extension.ftps" level="INFO" ></AsyncLogger>
60
        <AsyncLogger name="org.mule.modules.sap" level="INFO" ></AsyncLogger>
61
        <AsyncLogger name="com.mulesoft.extension.mq" level="INFO" ></AsyncLogger>
62
        <AsyncLogger name="com.mulesoft.mq" level="INFO" ></AsyncLogger>
63
        <AsyncLogger name="org.mule.extension.db" level="INFO" ></AsyncLogger>
64
        <AsyncLogger name="httpclient.wire" level="DEBUG" ></AsyncLogger>
65
        <AsyncLogger name="org.mule.transport.email" level="DEBUG" ></AsyncLogger>
66
    </Loggers>
67
</Configuration>
68



JSON Logger

JSON Logger is a component for logging the information, warning, errors. It logs the data in the form of JSON. It is recommended to use JSON Logger for your application and it logs the data in a well-formed way in any tools like Splunk, ELK, etc.

You can install JSON Logger in Anypoint Studio from Exchange.

Logger

Configure the JSON Logger as shown below.

JSON Logger

You can set the application name, application version and environment in the properties file.

XML
 




x
57


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
 
          
3
<mule xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
4
    xmlns:json-logger="http://www.mulesoft.org/schema/mule/json-logger"
5
    xmlns:api-gateway="http://www.mulesoft.org/schema/mule/api-gateway"
6
    xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
7
    http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
8
    http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd 
9
http://www.mulesoft.org/schema/mule/api-gateway http://www.mulesoft.org/schema/mule/api-gateway/current/mule-api-gateway.xsd
10
http://www.mulesoft.org/schema/mule/json-logger http://www.mulesoft.org/schema/mule/json-logger/current/mule-json-logger.xsd
11
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
12
    <http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="4dea45bf-d0c6-4ee8-baa0-0b8a9e508c88" basePath="/api/timezone" >
13
        <http:request-connection host="worldtimeapi.org" />
14
    </http:request-config>
15
    <configuration-properties doc:name="Configuration properties" doc:id="9dacbbe5-0ec7-4ce4-b094-ff89131a07cc" file="cloud.properties" />
16
 
          
17
    <global-property doc:name="Global Property" doc:id="7a60a2c8-efcf-4538-81c8-64248fe0dec4" name="mule.env" value="dev" />
18
    <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="694e8fba-882a-4f04-805b-50c66ecec1a3" >
19
        <http:listener-connection host="0.0.0.0" port="${http.private.port}" />
20
    </http:listener-config>
21
    <json-logger:config name="JSON_Logger_Config" doc:name="JSON Logger Config" doc:id="59e12b0a-d64d-4300-af40-23b29f11c2dc"/>
22
    <flow name="test-application-cloudFlow" doc:id="7db040d5-7309-4688-a4c5-fea0f43c6103">
23
        <http:listener doc:name="Listener" doc:id="da11b76c-b4d5-4140-a539-5841c4690b8c" config-ref="HTTP_Listener_config" path="/v1.0/timezone/{region}/{city}">
24
            <http:error-response statusCode="#[vars.httpStatusCode]" >
25
                <http:body ><![CDATA[#[payload]]]></http:body>
26
            </http:error-response>
27
        </http:listener>
28
        <http:request method="GET" doc:name="Request" doc:id="730aec0d-fb82-4430-8cf3-c14264a7e9ae" config-ref="HTTP_Request_configuration" path="/{region}/{city}">
29
            <http:uri-params ><![CDATA[#[output application/java
30
---
31
{
32
    city : attributes.uriParams.city,
33
    region : attributes.uriParams.region
34
}]]]></http:uri-params>
35
        </http:request>
36
        <json-logger:logger doc:name="Logger" doc:id="f2257ace-a8b0-4f5f-83d5-4ac8a710983f" config-ref="JSON_Logger_Config" message="#['Information']"/>
37
        <error-handler >
38
            <on-error-propagate enableNotifications="true" logException="true" doc:name="On Error Propagate" doc:id="1d5f427f-ceaa-4af1-8e2d-2be0aaf45b46" type="HTTP:FORBIDDEN">
39
                <ee:transform doc:name="Transform Message" doc:id="b978dae0-7538-4910-82ee-3c12236b6603" >
40
                    <ee:message >
41
                        <ee:set-payload ><![CDATA[%dw 2.0
42
output application/json
43
---
44
{
45
    error:error.description
46
}]]></ee:set-payload>
47
                    </ee:message>
48
                    <ee:variables >
49
                        <ee:set-variable variableName="httpStatusCode" ><![CDATA[403]]></ee:set-variable>
50
                    </ee:variables>
51
                </ee:transform>
52
                <json-logger:logger doc:name="Logger" doc:id="3c5e26da-4183-4318-9f6a-a07b86b717ff" config-ref="JSON_Logger_Config" message="Data From Timezone" priority="ERROR"/>
53
            </on-error-propagate>
54
        </error-handler>
55
    </flow>
56
</mule>



CloudFlow

Now, you can verify the logs in Splunk and it will be in JSON format.

Enable Splunk Logging For On-Premise MuleSoft Runtime 

For enabling the logging for On-Premise MuleSoft Runtime, you can use HTTP Appender.

You can add HTTP Appender in log4j2.xml located at $MULE_HOME/conf/

XML
 




x



1
<Http name="Splunk" url="http://localhost:8088/services/collector/raw">
2
            <Property name="Authorization" value="Splunk eert8e102-5f55-40ad-a047-b55a82245419"></Property>
3
            <PatternLayout pattern="%-5p %d [%t] [event: %X{correlationId}] %c: %m%n"></PatternLayout>
4
</Http>



This will allows sending logs to Splunk.

Full log4j2.xml

XML
 




x


1
<?xml version="1.0" encoding="UTF-8"?>
2
<Configuration>
3
    <Appenders>
4
        <Console name="Console" target="SYSTEM_OUT">
5
            <PatternLayout pattern="%-5p %d [%t] [event: %X{correlationId}] %c: %m%n" />
6
        </Console>
7
        <Console name="ConsoleLogUtil" target="SYSTEM_OUT">
8
            <PatternLayout pattern="%m%n" />
9
        </Console>
10
        <Http name="Splunk" url="http://localhost:8088/services/collector/raw">
11
            <Property name="Authorization" value="Splunk eert8e102-5f55-40ad-a047-b55a82245419"></Property>
12
            <PatternLayout pattern="%-5p %d [%t] [event: %X{correlationId}] %c: %m%n"></PatternLayout>
13
        </Http>
14
    </Appenders>
15
    <Loggers>
16
        <AsyncLogger
17
            name="org.mule.runtime.core.internal.processor.LoggerMessageProcessor"
18
            level="INFO" />
19
        <AsyncLogger name="com.mulesoft.agent" level="INFO" />
20
        <AsyncLogger name="org.mule.runtime.core.internal.logging"
21
            additivity="false" level="INFO">
22
            <AppenderRef ref="ConsoleLogUtil" />
23
        </AsyncLogger>
24
        <AsyncRoot level="INFO">
25
            <AppenderRef ref="Console" />
26
            <AppenderRef ref="Splunk" />
27
        </AsyncRoot>
28
        <AsyncLogger name="com.mulesoft.mule.runtime.gw" level="INFO" />
29
        <AsyncLogger name="com.mulesoft.extension.policies" level="INFO" />
30
        <AsyncLogger name="com.mulesoft.extension.gateway" level="INFO" />
31
        <AsyncLogger name="com.mulesoft.analytics" level="INFO" />
32
        <AsyncLogger name="org.mule" level="INFO" />
33
        <AsyncLogger name="com.mulesoft" level="INFO" />
34
    </Loggers>
35
</Configuration>



This is how you can enable Splunk logging using SplunkHTTP and HTTP Appender for MuleSoft applications.

Topics:
cloud ,cloudhub ,http ,logging ,mulesoft ,splunk ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}