[logback-user] Associating a per-class instance property with a Logger

ceki ceki at qos.ch
Thu Apr 19 17:26:26 CEST 2012


Hi George,

Comments inline.

On 19.04.2012 16:15, George C. Hawkins wrote:
> Hallo --
>
> We have a system where we have what I'll call groups.
>
> Each group has a numeric identifier and when a new group is created a
> corresponding large set of heterogeneous objects are created.
>
> These objects are not shared between groups.
>
> Whenever any of these objects log anything we always want to see the
> numeric identifier (of the group to which they belong) in the log message.

I take the above statement as the specification for what you wish to 
achieve.

[cut]

> logger.error("limit exceeded", groupId.args());
>
> I'm inclined to think using Markers would be better. I would create a
> Marker instance in every class where I also had a logger, and initialize
> it such that its name would return something like "groupId=" + groupId.
>
> However comments like the following on stackoverflow suggest this is an
> inappropriate use of Markers:
>
> http://stackoverflow.com/a/4167298/245602
>
> At the moment though I think I'll ignore this and uses Markers unless
> someone can suggest a better approach?

You could use markers. However, once a marker is created it lives until 
the app stops. To get around this problem you could create "detached"
markers. See the getDetachedMarkers() method in in MarkerFactory.

Instead of markers, I would suggest writing a conversion specifier [1], 
with conversion word %groupID and converter GroupIDConverter. Given that 
converters have access to all fields of the ILoggingEvent, including the 
parameters, GroupIDConverter could output the group id in the presence 
of a parameter of type GroupID.

class MyObject {
   Logger logger = LoggerFactory.getLogger(MyObject.class);

   public GroupID getGroupId() {
     return ...;
   }

   void foo() {
      logger.info("Doing foo", getGroupId());
   }
}

The trick here is to pass myObject's groupId as a parameter but have no 
corresponding anchor point, i.e. there is no '{}' in "Doing foo".

You could factor the code so that objects with groupIds log by emitting 
their groupId as the last parameter (with no corresponding '{}').

HTH,

[1] http://logback.qos.ch/manual/layouts.html#customConversionSpecifier

> Regards,
>
> /George

-- 
Ceki
http://twitter.com/#!/ceki


More information about the Logback-user mailing list