Menu

Runtime conditional formatting

Help
Lucas Bmd
2017-06-28
2017-06-28
  • Lucas Bmd

    Lucas Bmd - 2017-06-28

    Hi,

    I am trying to configure at runtime which attributes are logged and which aren't, based on some external condition. Would using a conditional formatter be a correct solution?

    I have been trying with:

    expr::if_ (filter)
    [
        true_formatter
    ]
    .else_
    [
        false_formatter
    ]
    

    but "filter" does not seem to accept an external boolean.

    For example, I would like to be able to enable / disable timestamp logging.

    bool timestamp_enabled = true ;
    
    ...
    
    logging::formatter formatter = expr::stream
    << expr::if_(timestamp_enabled)
    [
        expr::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f") << " | "
    ]
    << expr::smessage ;
    

    Thank you very much for your help!

    Lucas

     
  • Andrey Semashev

    Andrey Semashev - 2017-06-28

    First, you need to capture a reference to timestamp_enabled as a function object that supports being called as a filter. You can use Boost.Phoenix for that:

    expr::if_(boost::phoenix::cref(timestamp_enabled))
    

    Second, the formatter needs to start with expr::stream:

    expr::stream << expr::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f") << " | "
    

    Lastly, capturing the reference means you're not performing any thread synchronization when timestamp_enabled is accessed, which could result in a race condition. Do that only if you are certain log records will not be emitted from multiple threads.

    If you're in multithreaded environment then you either have to synchronize access to timestamp_enabled (e.g. use a mutex or wrap it in atomic) or avoid capturing the reference in the first place by updating the filter instead whenever you need to change the behavior. From performance standpoint, adding synchronization may impair concurrency when emitting log records, so the latter solution is preferable, unless you need to change the filter very often.

     
  • Lucas Bmd

    Lucas Bmd - 2017-06-29

    Thank you Andrey for your prompt reply.
    It totally worked!

    Have a good day,

    Lucas

     

Log in to post a comment.