quarkiverse / quarkus-logging-json

Quarkus logging extension outputting the logging in json.
Apache License 2.0
62 stars 28 forks source link

Adding dynamic additional value? #268

Open dimon37 opened 11 months ago

dimon37 commented 11 months ago

Is it possible to add a dynamic value to log entry? SPecifically, i want to add request ID, but so far I saw no mechanism. Seems like pretty frequently required feature

fbuatois commented 11 months ago

Hello, maybe you figured it out already, but I managed to make it work. I don't know if it is the proper way though. But it works for me :

What I did was :

I defined the class "MyJsonProvider" in my project, as described in the readme, and added two variables, one representing the value-name for the property I wanted to add, and an other one for the value of the property itself. It looks like that :

package my.package;

import javax.inject.Singleton;
import java.io.IOException;

import io.quarkiverse.loggingjson.JsonProvider;
import io.quarkiverse.loggingjson.JsonGenerator;
import org.jboss.logmanager.ExtLogRecord;

@Singleton
public class MyJsonProvider implements JsonProvider {

    public String FIELD_NAME= "field.name";
    public String FIELD_VALUE= null;

    @Override
    public void writeTo(JsonGenerator generator, ExtLogRecord event) throws IOException {
        generator.writeStringField(FIELD_NAME, FIELD_VALUE);
    }
}

Then, in the class where I wanted to use this property dynamically, I injected the dependence like so :

package my.other.package

import javax.inject.Inject;

public class MyClass {
    // ...
    @Inject
    MyJsonProvider jsonProvider;
    // ...

    public void myMethod() {
        // defining my value
        String value = "Value1234";

        jsonProvider.FIELD_VALUE = value;
    }
}

Without doing anything else besides adding the proper configuration in my application.properties as explained in the readme, this works for me.

I assume this works for as many fields as you want. Using this method I couldn't tell the limitations but yeah, give it a try.