Logging to AWS Cloudwatch Logs
Learn how to easily configure the slf4j logging framework to use AWS Cloudwatch to store your logs, for AWS or on-premise.
Join the DZone community and get the full member experience.
Join For FreeIn case you are already using slf4j as your logging framework, this article will show you how easy
it is to configure your logging to use AWS Cloudwatch for storing your logs.
This can be used for applications which are running on AWS or on-premise.
You can find the library on GitHub, which does it by using logback as the slf4j backend.
In the following steps, you can see a minimal configuration for an appender which assumes that the application is running on an EC2 instance with an IAM profile which the rights to
access Cloudwatch Logs:
<appender name="cloud-watch" class="io.github.dibog.AwsLogAppender">
<createLogGroup>true</createLogGroup>
<groupName>group-name</groupName>
<streamName>stream-name</streamName>
<dateFormat>yyyyMMdd_HHmm</dateFormat>
<layout>
<pattern>[%thread] %-5level %logger{35} - %msg %n</pattern>
</layout>
</appender>
The tag <createLogGroup> indicates if the appender should create the log group if it does not
exist. For that, you need to have thelogs:CreateLogGroup
andlogs:DescribeLogGroups
permissions.<groupName> lets you specify the name of the log group.
<streamName> lets you either specify the name of the stream or its prefix.
<dateFormat> If you specify a date format, the actual stream name is built out of the above
specified streamName concatenated with the string computed by the dateFormat.
As soon as that name changes, the existing stream will be closed and a new one created.In the <layout>, you can describe the format in which the log event should be displayed.
In case your application is not running on AWS or you don't want to use the IAM Profile of the
EC2 instance, you can also specify the AWS credentials; you need to have at least the permissionslogs:DescribeLogStreams
andcredentialslogs:PutLogEvents
:
<appender name="cloud-watch" class="io.github.dibog.AwsLogAppender">
<awsConfig>
<credentials>
<accessKeyId></accessKeyId>
<secretAccessKey></secretAccessKey>
</credentials>
<region></region>
<clientConfig class="com.amazonaws.ClientConfiguration">
<proxyHost></proxyHost>
<proxyPort></proxyPort>
</clientConfig>
</awsConfig>
<createLogGroup>false</createLogGroup>
<queueLength>100</queueLength>
<groupName>group-name</groupName>
<streamName>stream-name</streamName>
<dateFormat>yyyyMMdd_HHmm</dateFormat>
<layout>
<pattern>[%thread] %-5level %logger{35} - %msg %n</pattern>
</layout>
</appender>
Enter your accessKey and the secretAccess in the correct location. You also have to specify which
AWS Region should be used. The ClientConfiguration is only necessary if you have some proxy issues. Please refer to these docs for details.
Opinions expressed by DZone contributors are their own.
Comments