GitHub user ppkarwasz added a comment to the discussion: Help with migrating 
from log4j to log4j2 (we also use a slf4j -> log4j)

Hi @paladox,  

### On your current approach

In your current code you **stop** `async` before creating a new one. That 
means:  

- For a short time no appender is available at all.  
- Even worse, the `async` field is temporarily `null`.  

A safer pattern is to build the replacement first and only swap the reference 
at the very end. That way you never expose a “gap” where logging calls see no 
appender.  

Also note: since you’re not attaching the `AsyncAppender` to any logger, 
there’s no need to register it with the active `LoggerContext` configuration. 
The only reason you need a `Configuration` is because the `AsyncAppender` 
builder requires it in order to look up its referenced appenders. In this case 
you can use your own private `NullConfiguration` instance instead of modifying 
the shared context.  

### Programmatic configuration options

If the goal is to combine a file-based configuration with some programmatically 
defined components, there are two main approaches:  

1. **CompositeConfiguration + ConfigurationBuilder (recommended)**  
   - Use 
[CompositeConfiguration](https://logging.apache.org/log4j/2.x/manual/customconfig.html#CompositeConfiguration)
 to merge your static file with a dynamically built config.  
   - Build the dynamic part using 
[ConfigurationBuilder](https://logging.apache.org/log4j/2.x/manual/customconfig.html#ConfigurationBuilder).
  
   - Advantage: this doesn’t require instantiating or managing any Core 
components yourself: you’re just describing what should exist, and Log4j Core 
builds and wires everything.  
   - Limitation: attributes are provided as strings, so it’s not 100% 
type-safe, though the builder offers type-safe helpers for the common ones.  

2. **Custom ConfigurationFactory**  
   - Implement your own `ConfigurationFactory` that loads a standard config 
(delegating to an existing factory) and then applies programmatic 
modifications.  
   - Advantage: fully type-safe, since you’re working directly with 
configuration objects. The lifecycle is handled for you because the 
configuration is only started after the factory returns it.  
   - Useful if you want strict control over configuration composition without 
relying on string-based attributes.  



GitHub link: 
https://github.com/apache/logging-log4j2/discussions/3914#discussioncomment-14348063

----
This is an automatically sent email for dev@logging.apache.org.
To unsubscribe, please send an email to: dev-unsubscr...@logging.apache.org

Reply via email to