elastic / ecs-logging-java

https://www.elastic.co/guide/en/ecs-logging/java/current/intro.html
Apache License 2.0
141 stars 75 forks source link

Allow subclasses to insert custom fields #151

Closed echatman closed 2 years ago

echatman commented 2 years ago

Protected method that subclasses can override to insert arbitrary custom fields in the logback encoder. https://github.com/elastic/ecs-logging-java/issues/147

apmmachine commented 2 years ago

:green_heart: Build Succeeded

the below badges are clickable and redirect to their specific view in the CI or DOCS Pipeline View Test View Changes Artifacts preview preview

Expand to view the summary

#### Build stats * Start Time: 2021-10-19T06:25:44.818+0000 * Duration: 5 min 23 sec * Commit: 3ca0dca6b32298ecb4ec72a6adf01afc17ee7d9b #### Test stats :test_tube: | Test | Results | | ------------ | :-----------------------------: | | Failed | 0 | | Passed | 171 | | Skipped | 0 | | Total | 171 |

:robot: GitHub comments

To re-run your PR in the CI, just comment with:

felixbarny commented 2 years ago

/test

felixbarny commented 2 years ago

Thank you!

lbuyse commented 1 year ago

Hello ,

I need exactly the same functionality. Allthough i can't get my custom EcsEncoder extension class to work with spring boot and logback. Can i find an example of class like this somewhere ... ? i am wondering if overriding the addCustomFields method is enough.

Many thanks

echatman commented 1 year ago

Yes you just create a class that extends EcsEncoder and override the addCustomFields method to add in whatever you need. Then you use it by defining your own custom appender - you can copy from ecs-console-appender.xml or ecs-file-appender.xml and change the appender name and encoder class.

So a full logback-spring.xml config could look like this:

<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="co/elastic/logging/logback/boot/ecs-console-appender.xml" />
    <appender name="CUSTOM_ECS_JSON_CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="com.echatman.MyCustomEcsEncoder">
            <serviceName>${SERVICE_NAME:-spring-boot-application}</serviceName>
            <!-- any other properties you want to set on your custom class go here -->
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="CUSTOM_ECS_JSON_CONSOLE" />
    </root>
</configuration>
lbuyse commented 1 year ago

Hello , Thats exactly what i did but while debugging i've realized i wrote a bug in my custom encoder which caused a nullpointer in my encoder that caused it not to write logs. I solved it and it works as expected , many thanks for your help and sorry to waste your time. Kind regards