expressions.qbk 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. [/
  2. Copyright Andrey Semashev 2007 - 2016.
  3. Distributed under the Boost Software License, Version 1.0.
  4. (See accompanying file LICENSE_1_0.txt or copy at
  5. http://www.boost.org/LICENSE_1_0.txt)
  6. This document is a part of Boost.Log library documentation.
  7. /]
  8. [section:expressions Lambda expressions]
  9. As it was pointed out in [link log.tutorial tutorial], filters and formatters can be specified as Lambda expressions with placeholders for attribute values. This section will describe the placeholders that can be used to build more complex Lambda expressions.
  10. There is also a way to specify the filter in the form of a string template. This can be useful for initialization from the application settings. This part of the library is described [link log.detailed.utilities.setup.filter_formatter here].
  11. [section:attr Generic attribute placeholder]
  12. #include <``[boost_log_expressions_attr_fwd_hpp]``>
  13. #include <``[boost_log_expressions_attr_hpp]``>
  14. The [funcref boost::log::expressions::attr attr] placeholder represents an attribute value in template expressions. Given the record view or a set of attribute values, the placeholder will attempt to extract the specified attribute value from the argument upon invocation. This can be roughly described with the following pseudo-code:
  15. logging::value_ref< T, TagT > val = expr::attr< T, TagT >(name)(rec);
  16. where `val` is the [link log.detailed.utilities.value_ref reference] to the extracted value, `name` and `T` are the attribute value [link log.detailed.attributes.related_components.attribute_name name] and type, `TagT` is an optional tag (we'll return to it in a moment) and `rec` is the log [link log.detailed.core.record record view] or [link log.detailed.attributes.related_components.attribute_value_set attribute value set]. `T` can be a __boost_mpl__ type sequence with possible expected types of the value; the extraction will succeed if the type of the value matches one of the types in the sequence.
  17. The `attr` placeholder can be used in __boost_phoenix__ expressions, including the `bind` expression.
  18. [example_tutorial_filtering_bind]
  19. The placeholder can be used both in filters and formatters:
  20. sink->set_filter
  21. (
  22. expr::attr< int >("Severity") >= 5 &&
  23. expr::attr< std::string >("Channel") == "net"
  24. );
  25. sink->set_formatter
  26. (
  27. expr::stream
  28. << expr::attr< int >("Severity")
  29. << " [" << expr::attr< std::string >("Channel") << "] "
  30. << expr::smessage
  31. );
  32. The call to `set_filter` registers a composite filter that consists of two elementary subfilters: the first one checks the severity level, and the second checks the channel name. The call to `set_formatter` installs a formatter that composes a string containing the severity level and the channel name along with the message text.
  33. [section:fallback_policies Customizing fallback policy]
  34. By default, when the requested attribute value is not found in the record, `attr` will return an empty reference. In case of filters, this will result in `false` in any ordering expressions, and in case of formatters the output from the placeholder will be empty. This behavior can be changed:
  35. * To throw an exception ([class_log_missing_value] or [class_log_invalid_type], depending on the reason of the failure). Add the `or_throw` modifier:
  36. sink->set_filter
  37. (
  38. expr::attr< int >("Severity").or_throw() >= 5 &&
  39. expr::attr< std::string >("Channel").or_throw() == "net"
  40. );
  41. * To use a default value instead. Add the `or_default` modifier with the desired default value:
  42. sink->set_filter
  43. (
  44. expr::attr< int >("Severity").or_default(0) >= 5 &&
  45. expr::attr< std::string >("Channel").or_default(std::string("general")) == "net"
  46. );
  47. [tip You can also use the [link log.detailed.expressions.predicates.has_attr `has_attr`] predicate to implement filters and formatters conditional on the attribute value presence.]
  48. The default behavior is also accessible through the `or_none` modifier. The modified placeholders can be used in filters and formatters just the same way as the unmodified ones.
  49. In `bind` expressions, the bound function object will still receive the [link log.detailed.utilities.value_ref `value_ref`]-wrapped values in place of the modified `attr` placeholder. Even though both `or_throw` and `or_default` modifiers guarantee that the bound function will receive a filled reference, [link log.detailed.utilities.value_ref `value_ref`] is still needed if the value type is specified as a type sequence. Also, the reference wrapper may contain a tag type which may be useful for formatting customization.
  50. [endsect]
  51. [section:tags Attribute tags and custom formatting operators]
  52. The `TagT` type in the [link log.detailed.expressions.attr abstract description] of `attr` above is optional and by default is `void`. This is an attribute tag which can be used to customize the output formatters produce for different attributes. This tag is forwarded to the [link log.detailed.utilities.manipulators.to_log `to_log`] manipulator when the extracted attribute value is put to a stream (this behavior is warranted by [link log.detailed.utilities.value_ref `value_ref`] implementation). Here's a quick example:
  53. [example_expressions_attr_formatter_stream_tag]
  54. [@boost:/libs/log/example/doc/expressions_attr_fmt_tag.cpp See the complete code].
  55. Here we specify a different formatting operator for the severity level wrapped in the [link log.detailed.utilities.manipulators.to_log `to_log_manip`] manipulator marked with the tag `severity_tag`. This operator will be called when log records are formatted while the regular `operator<<` will be used in other contexts.
  56. [endsect]
  57. [endsect]
  58. [section:attr_keywords Defining attribute keywords]
  59. #include <``[boost_log_expressions_keyword_fwd_hpp]``>
  60. #include <``[boost_log_expressions_keyword_hpp]``>
  61. Attribute keywords can be used as replacements for the [link log.detailed.expressions.attr `attr`] placeholders in filters and formatters while providing a more concise and less error prone syntax. An attribute keyword can be declared with the [macroref BOOST_LOG_ATTRIBUTE_KEYWORD] macro:
  62. BOOST_LOG_ATTRIBUTE_KEYWORD(keyword, "Keyword", type)
  63. Here the macro declares a keyword `keyword` for an attribute named "Keyword" with the value type of `type`. Additionally, the macro defines an attribute tag type `keyword` within the `tag` namespace. We can rewrite the previous example in the following way:
  64. [example_expressions_keyword_formatter_stream_tag]
  65. Attribute keywords behave the same way as the [link log.detailed.expressions.attr `attr`] placeholders and can be used both in filters and formatters. The `or_throw` and `or_default` modifiers are also supported.
  66. Keywords can also be used in attribute value lookup expressions in log records and attribute value sets:
  67. [example_expressions_keyword_lookup]
  68. [endsect]
  69. [section:record Record placeholder]
  70. #include <``[boost_log_expressions_record_hpp]``>
  71. The `record` placeholder can be used in `bind` expressions to pass the whole log [link log.detailed.core.record record view] to the bound function object.
  72. void my_formatter(logging::formatting_ostream& strm, logging::record_view const& rec)
  73. {
  74. // ...
  75. }
  76. namespace phoenix = boost::phoenix;
  77. sink->set_formatter(phoenix::bind(&my_formatter, expr::stream, expr::record));
  78. [note In case of filters, the placeholder will correspond to the [link log.detailed.attributes.related_components.attribute_value_set set of attribute values] rather than the log record itself. This is because the record is not constructed yet at the point of filtering, and filters only operate on the set of attribute values.]
  79. [endsect]
  80. [section:message Message text placeholders]
  81. #include <``[boost_log_expressions_message_hpp]``>
  82. Log records typically contain a special attribute "Message" with the value of one of the string types (more specifically, an `std::basic_string` specialization). This attribute contains the text of the log message that is constructed at the point of the record creation. This attribute is only constructed after filtering, so filters cannot use it. There are several keywords to access this attribute value:
  83. * `smessage` - the attribute value is expected to be an `std::string`
  84. * `wmessage` - the attribute value is expected to be an `std::wstring`
  85. * `message` - the attribute value is expected to be an `std::string` or `std::wstring`
  86. The `message` keyword has to dispatch between different string types, so it is slightly less efficient than the other two keywords. If the application is able to guarantee the fixed character type of log messages, it is advised to use the corresponding keyword for better performance.
  87. // Sets up a formatter that will ignore all attributes and only print log record text
  88. sink->set_formatter(expr::stream << expr::message);
  89. [endsect]
  90. [section:predicates Predicate expressions]
  91. This section describes several expressions that can be used as predicates in filtering expressions.
  92. [section:has_attr Attribute presence filter]
  93. #include <``[boost_log_expressions_predicates_has_attr_hpp]``>
  94. The filter [funcref boost::log::expressions::has_attr `has_attr`] checks if an attribute value with the specified name and, optionally, type is attached to a log record. If no type specified to the filter, the filter returns `true` if any value with the specified name is found. If an MPL-compatible type sequence in specified as a value type, the filter returns `true` if a value with the specified name and one of the specified types is found.
  95. This filter is usually used in conjunction with [link log.detailed.expressions.formatters.conditional conditional formatters], but it also can be used as a quick filter based on the log record structure. For example, one can use this filter to extract statistic records and route them to a specific sink.
  96. [example_expressions_has_attr_stat_accumulator]
  97. [@boost:/libs/log/example/doc/expressions_has_attr_stat_accum.cpp See the complete code].
  98. In this example, log records emitted with the `PUT_STAT` macro will be directed to the `my_stat_accumulator` sink backend, which will accumulate the changes passed in the "Change" attribute values. All other records (even those made through the same logger) will be passed to the filter sink. This is achieved with the mutually exclusive filters set for the two sinks.
  99. Please note that in the example above we extended the library in two ways: we defined a new sink backend `my_stat_accumulator` and a new macro `PUT_STAT`. Also note that `has_attr` can accept attribute keywords to identify the attribute to check.
  100. [endsect]
  101. [section:is_in_range Range checking filter]
  102. #include <``[boost_log_expressions_predicates_is_in_range_hpp]``>
  103. The [funcref boost::log::expressions::is_in_range `is_in_range`] predicate checks that the attribute value fits in the half-open range (i.e. it returns `true` if the attribute value `x` satisfies the following condition: `left <= x < right`). For example:
  104. sink->set_filter
  105. (
  106. // drops all records that have level below 3 or greater than 4
  107. expr::is_in_range(expr::attr< int >("Severity"), 3, 5)
  108. );
  109. The attribute can also be identified by an attribute keyword or name and type:
  110. sink->set_filter
  111. (
  112. expr::is_in_range(severity, 3, 5)
  113. );
  114. sink->set_filter
  115. (
  116. expr::is_in_range< int >("Severity", 3, 5)
  117. );
  118. [endsect]
  119. [section:simple_string_matching Simple string matching filters]
  120. #include <``[boost_log_expressions_predicates_begins_with_hpp]``>
  121. #include <``[boost_log_expressions_predicates_ends_with_hpp]``>
  122. #include <``[boost_log_expressions_predicates_contains_hpp]``>
  123. Predicates [funcref boost::log::expressions::begins_with `begins_with`], [funcref boost::log::expressions::ends_with `ends_with`] and [funcref boost::log::expressions::contains `contains`] provide an easy way of matching string attribute values. As follows from their names, the functions construct filters that return `true` if an attribute value begins with, ends with or contains the specified substring, respectively. The string comparison is case sensitive.
  124. sink->set_filter
  125. (
  126. // selects only records that are related to Russian web domains
  127. expr::ends_with(expr::attr< std::string >("Domain"), ".ru")
  128. );
  129. The attribute can also be identified by an attribute keyword or name and type.
  130. [endsect]
  131. [section:advanced_string_matching Advanced string matching filter]
  132. #include <``[boost_log_expressions_predicates_matches_hpp]``>
  133. // Supporting headers
  134. #include <``[boost_log_support_regex_hpp]``>
  135. #include <``[boost_log_support_std_regex_hpp]``>
  136. #include <``[boost_log_support_xpressive_hpp]``>
  137. #include <``[boost_log_support_spirit_qi_hpp]``>
  138. #include <``[boost_log_support_spirit_classic_hpp]``>
  139. The [funcref boost::log::expressions::matches `matches`] function creates a filter that apples a regular expression or a parser to a string attribute value. The regular expression can be provided by __boost_regex__ or __boost_xpressive__. Parsers from __boost_spirit__ and __boost_spirit2__ are also supported. The filter returns `true` if the regular expression matches or the parser successfully parses the attribute value.
  140. [note In order to use this predicate, a corresponding supporting header should also be included.]
  141. sink->set_filter
  142. (
  143. expr::matches(expr::attr< std::string >("Domain"), boost::regex("www\\..*\\.ru"))
  144. );
  145. The attribute can also be identified by an attribute keyword or name and type.
  146. [endsect]
  147. [section:channel_severity_filter Severity threshold per channel filter]
  148. #include <``[boost_log_expressions_predicates_channel_severity_filter_hpp]``>
  149. This filter is aimed for a specific but commonly encountered use case. The [funcref boost::log::expressions::channel_severity_filter `channel_severity_filter`] function creates a predicate that will check log record severity levels against a threshold. The predicate allows setting different thresholds for different channels. The mapping between channel names and severity thresholds can be filled in `std::map` style by using the subscript operator or by calling `add` method on the filter itself (the [class_expressions_channel_severity_filter_actor] instance). Let's see an example:
  150. [example_expressions_channel_severity_filter]
  151. [@boost:/libs/log/example/doc/expressions_channel_severity_filter.cpp See the complete code].
  152. The filter for the console sink is composed from the [class_expressions_channel_severity_filter_actor] filter and a general severity level check. This general check will be used when log records do not have a channel attribute or the channel name is not one of those specified in [class_expressions_channel_severity_filter_actor] initialization. It should be noted that it is possible to set the default result of the threshold filter that will be used in this case; the default result can be set by the `set_default` method. The [class_expressions_channel_severity_filter_actor] filter is set up to limit record severity levels for channels "general", "network" and "gui" - all records in these channels with levels below the specified thresholds will not pass the filter and will be ignored.
  153. The threshold filter is implemented as an equivalent to `std::map` over the channels, which means that the channel value type must support partial ordering. Obviously, the severity level type must also support ordering to be able to be compared against thresholds. By default the predicate will use `std::less` equivalent for channel name ordering and `std::greater_equal` equivalent to compare severity levels. It is possible to customize the ordering predicates. Consult the reference of the [class_expressions_channel_severity_filter_actor] class and [funcref boost::log::expressions::channel_severity_filter `channel_severity_filter`] generator to see the relevant template parameters.
  154. [endsect]
  155. [section:is_debugger_present Debugger presence filter]
  156. #include <``[boost_log_expressions_predicates_is_debugger_present_hpp]``>
  157. This filter is implemented for Windows only. The `is_debugger_present` filter returns `true` if the application is run under a debugger and `false` otherwise. It does not use any attribute values from the log record. This predicate is typically used with the [link log.detailed.sink_backends.debugger debugger output] sink.
  158. [example_sinks_debugger]
  159. [@boost:/libs/log/example/doc/sinks_debugger.cpp See the complete code].
  160. [endsect]
  161. [endsect]
  162. [section:formatters Formatting expressions]
  163. As was noted in the [link log.tutorial.formatters tutorial], the library provides several ways of expressing formatters, most notable being with a stream-style syntax and __boost_format__-style expression. Which of the two formats is chosen is determined by the appropriate anchor expression. To use stream-style syntax one should begin the formatter definition with the `stream` keyword, like that:
  164. #include <``[boost_log_expressions_formatters_stream_hpp]``>
  165. sink->set_formatter(expr::stream << expr1 << expr2 << ... << exprN);
  166. Here expressions `expr1` through `exprN` may be either manipulators, described in this section, or other expressions resulting in an object that supports putting into an STL-stream.
  167. To use __boost_format__-style syntax one should use `format` construct:
  168. #include <``[boost_log_expressions_formatters_format_hpp]``>
  169. sink->set_formatter(expr::format("format string") % expr1 % expr2 % ... % exprN);
  170. The format string passed to the `format` keyword should contain positional placeholders for the appropriate expressions. In the case of wide-character logging the format string should be wide. Expressions `expr1` through `exprN` have the same meaning as in stream-like variant. It should be noted though that using stream-like syntax usually results in a faster formatter than the one constructed with the `format` keyword.
  171. Another useful way of expressing formatters is by using string templates. This part of the library is described in [link log.detailed.utilities.setup.filter_formatter this] section and is mostly intended to support initialization from the application settings.
  172. [section:date_time Date and time formatter]
  173. #include <``[boost_log_expressions_formatters_date_time_hpp]``>
  174. // Supporting headers
  175. #include <``[boost_log_support_date_time_hpp]``>
  176. The library provides the [funcref boost::log::expressions::format_date_time `format_date_time`] formatter dedicated to date and time-related attribute value types. The function accepts the attribute value name and the format string compatible with __boost_date_time__.
  177. sink->set_formatter
  178. (
  179. expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S")
  180. );
  181. The attribute value can alternatively be identified with the [link log.detailed.expressions.attr `attr`] placeholder or the [link log.detailed.expressions.attr_keywords attribute keyword].
  182. The following placeholders are supported in the format string:
  183. [table Date format placeholders
  184. [[Placeholder][Meaning][Example]]
  185. [[%a] [Abbreviated weekday name]["Mon" => Monday]]
  186. [[%A] [Long weekday name]["Monday"]]
  187. [[%b] [Abbreviated month name]["Feb" => February]]
  188. [[%B] [Long month name]["February"]]
  189. [[%d] [Numeric day of month with leading zero]["01"]]
  190. [[%e] [Numeric day of month with leading space][" 1"]]
  191. [[%m] [Numeric month, 01-12]["01"]]
  192. [[%w] [Numeric day of week, 1-7]["1"]]
  193. [[%y] [Short year]["12" => 2012]]
  194. [[%Y] [Long year]["2012"]]
  195. ]
  196. [table Time format placeholders
  197. [[Placeholder][Meaning][Example]]
  198. [[%f] [Fractional seconds with leading zeros]["000231"]]
  199. [[%H, %O] [Hours in 24 hour clock or hours in time duration types with leading zero if less than 10]["07"]]
  200. [[%I] [Hours in 12 hour clock with leading zero if less than 10]["07"]]
  201. [[%k] [Hours in 24 hour clock or hours in time duration types with leading space if less than 10][" 7"]]
  202. [[%l] [Hours in 12 hour clock with leading space if less than 10][" 7"]]
  203. [[%M] [Minutes]["32"]]
  204. [[%p] [AM/PM mark, uppercase]["AM"]]
  205. [[%P] [AM/PM mark, lowercase]["am"]]
  206. [[%q] [ISO time zone]["-0700" => Mountain Standard Time]]
  207. [[%Q] [Extended ISO time zone]["-05:00" => Eastern Standard Time]]
  208. [[%S] [Seconds]["26"]]
  209. ]
  210. [table Miscellaneous placeholders
  211. [[Placeholder][Meaning][Example]]
  212. [[%-] [Negative sign in case of time duration, if the duration is less than zero]["-"]]
  213. [[%+] [Sign of time duration, even if positive]["+"]]
  214. [[%%] [An escaped percent sign]["%"]]
  215. [[%T] [Extended ISO time, equivalent to "%H:%M:%S"]["07:32:26"]]
  216. ]
  217. Note that in order to use this formatter you will also have to include a supporting header. When [boost_log_support_date_time_hpp] is included, the formatter supports the following types of __boost_date_time__:
  218. * Date and time types: `boost::posix_time::ptime` and `boost::local_time::local_date_time`.
  219. * Gregorian date type: `boost::gregorian::date`.
  220. * Time duration types: `boost::posix_time::time_duration` as well as all the specialized time units such as `boost::posix_time::seconds`, including subsecond units.
  221. * Date duration types: `boost::gregorian::date_duration`.
  222. [tip __boost_date_time__ already provides formatting functionality implemented as a number of locale facets. This functionality can be used instead of this formatter, although the formatter is expected to provide better performance.]
  223. [endsect]
  224. [section:named_scope Named scope formatter]
  225. #include <``[boost_log_expressions_formatters_named_scope_hpp]``>
  226. The formatter [funcref boost::log::expressions::format_named_scope `format_named_scope`] is intended to add support for flexible formatting of the [link log.detailed.attributes.named_scope named scope] attribute values. The basic usage is quite straightforward and its result is similar to what [link log.detailed.expressions.attr `attr`] provides:
  227. // Puts the scope stack from outer ones towards inner ones: outer scope -> inner scope
  228. sink->set_formatter(expr::stream << expr::format_named_scope("Scopes", "%n"));
  229. The first argument names the attribute and the second is the format string. The string can contain the following placeholders:
  230. [table Named scope format placeholders
  231. [[Placeholder][Meaning][Example]]
  232. [[%n] [Scope name]["void bar::foo()"]]
  233. [[%c] [Function name, if the scope is denoted with `BOOST_LOG_FUNCTION`, otherwise the full scope name. See the note below.]["bar::foo"]]
  234. [[%C] [Function name, without the function scope, if the scope is denoted with `BOOST_LOG_FUNCTION`, otherwise the full scope name. See the note below.]["foo"]]
  235. [[%f] [Source file name of the scope]["/home/user/project/foo.cpp"]]
  236. [[%F] [Source file name of the scope, without the path]["foo.cpp"]]
  237. [[%l] [Line number in the source file]["45"]]
  238. ]
  239. [note As described in the [link log.detailed.attributes.named_scope named scope] attribute description, it is possible to use `BOOST_LOG_FUNCTION` macro to automatically generate scope names from the enclosing function name. Unfortunately, the actual format of the generated strings is compiler-dependent and in many cases it includes the complete signature of the function. When "%c" or "%C" format flag is specified, the library attempts to parse the generated string to extract the function name. Since C++ syntax is very context dependent and complex, it is not possible to parse function signature correctly in all cases, so the library is basically guessing. Depending on the string format, this may fail or produce incorrect results. In particular, type conversion operators can pose problems for the parser. In case if the parser fails to recognize the function signature the library falls back to using the whole string (i.e. behave equivalent to the "%n" flag). To alleviate the problem the user can replace the problematic `BOOST_LOG_FUNCTION` usage with the `BOOST_LOG_NAMED_SCOPE` macro and explicitly write the desired scope name. Scope names denoted with `BOOST_LOG_NAMED_SCOPE` will not be interpreted by the library and will be output as is. In general, for portability and runtime performance reasons it is preferable to always use `BOOST_LOG_NAMED_SCOPE` and "%n" format flag.]
  240. While the format string describes the presentation of each named scope in the list, the following named arguments allow to customize the list traversal and formatting:
  241. * `format`. The named scope format string, as described above. This parameter is used to specify the format when other named parameters are used.
  242. * `iteration`. The argument describes the direction of iteration through scopes. Can have values `forward` (default) or `reverse`.
  243. * `delimiter`. The argument can be used to specify the delimiters between scopes. The default delimiter depends on the `iteration` argument. If `iteration == forward` the default `delimiter` will be "->", otherwise it will be "<-".
  244. * `depth`. The argument can be used to limit the number of scopes to put to log. The formatter will print `depth` innermost scopes and, if there are more scopes left, append an ellipsis to the written sequence. By default the formatter will write all scope names.
  245. * `incomplete_marker`. The argument can be used to specify the string that is used to indicate that the list has been limited by the `depth` argument. By default the "..." string is used as the marker.
  246. * `empty_marker`. The argument can be used to specify the string to output in case if the scope list is empty. By default nothing is output in this case.
  247. Here are a few usage examples:
  248. // Puts the scope stack in reverse order:
  249. // inner scope (file:line) <- outer scope (file:line)
  250. sink->set_formatter
  251. (
  252. expr::stream
  253. << expr::format_named_scope(
  254. "Scopes",
  255. keywords::format = "%n (%f:%l)",
  256. keywords::iteration = expr::reverse)
  257. );
  258. // Puts the scope stack in reverse order with a custom delimiter:
  259. // inner scope | outer scope
  260. sink->set_formatter
  261. (
  262. expr::stream
  263. << expr::format_named_scope(
  264. "Scopes",
  265. keywords::format = "%n",
  266. keywords::iteration = expr::reverse,
  267. keywords::delimiter = " | ")
  268. );
  269. // Puts the scope stack in forward order, no more than 2 inner scopes:
  270. // ... outer scope -> inner scope
  271. sink->set_formatter
  272. (
  273. expr::stream
  274. << expr::format_named_scope(
  275. "Scopes",
  276. keywords::format = "%n",
  277. keywords::iteration = expr::forward,
  278. keywords::depth = 2)
  279. );
  280. // Puts the scope stack in reverse order, no more than 2 inner scopes:
  281. // inner scope <- outer scope <<and more>>...
  282. sink->set_formatter
  283. (
  284. expr::stream
  285. << expr::format_named_scope(
  286. "Scopes",
  287. keywords::format = "%n",
  288. keywords::iteration = expr::reverse,
  289. keywords::incomplete_marker = " <<and more>>..."
  290. keywords::depth = 2)
  291. );
  292. [tip An empty string can be specified as the `incomplete_marker` parameter, in which case there will be no indication that the list was truncated.]
  293. [endsect]
  294. [section:conditional Conditional formatters]
  295. #include <``[boost_log_expressions_formatters_if_hpp]``>
  296. There are cases when one would want to check some condition about the log record and format it depending on that condition. One example of such a need is formatting an attribute value depending on its runtime type. The general syntax of the conditional formatter is as follows:
  297. expr::if_ (filter)
  298. [
  299. true_formatter
  300. ]
  301. .else_
  302. [
  303. false_formatter
  304. ]
  305. Those familiar with __boost_phoenix__ lambda expressions will find this syntax quite familiar. The `filter` argument is a filter that is applied to the record being formatted. If it returns `true`, the `true_formatter` is executed, otherwise `false_formatter` is executed. The `else_` section with `false_formatter` is optional. If it is omitted and `filter` yields `false`, no formatter is executed. Here is an example:
  306. sink->set_formatter
  307. (
  308. expr::stream
  309. // First, put the current time
  310. << expr::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << " "
  311. << expr::if_ (expr::has_attr< int >("ID"))
  312. [
  313. // if "ID" is present then put it to the record
  314. expr::stream << expr::attr< int >("ID")
  315. ]
  316. .else_
  317. [
  318. // otherwise put a missing marker
  319. expr::stream << "--"
  320. ]
  321. // and after that goes the log record text
  322. << " " << expr::message
  323. );
  324. [endsect]
  325. [section:auto_newline Automatic newline insertion]
  326. #include <``[boost_log_expressions_formatters_auto_newline_hpp]``>
  327. This is an adaptation of the [link log.detailed.utilities.manipulators.auto_newline `auto_newline` manipulator] for formatter expressions. The `auto_newline` formatter can be useful, for example, if log messages generated by one source are terminated with a newline character (and that behavior cannot be changed easily), and other messages are not. The formatter will ensure that all messages are reliably terminated with a newline and there are no duplicate newline characters. Like the manipulator, it will insert a newline unless the last character inserted into the stream before it was a newline. For example:
  328. sink->set_formatter
  329. (
  330. expr::stream
  331. // Ensure that the sink outputs one message per line,
  332. // regardless whether the message itself ends with a newline or not
  333. << expr::message << expr::auto_newline
  334. );
  335. [endsect]
  336. [section:decorators Character decorators]
  337. There are times when one would like to additionally post-process the composed string before passing it to the sink backend. For example, in order to store log into an XML file the formatted log record should be checked for special characters that have a special meaning in XML documents. This is where decorators step in.
  338. [note Unlike most other formatters, decorators are dependent on the character type of the formatted output and this type cannot be deduced from the decorated formatter. By default, the character type is assumed to be `char`. If the formatter is used to compose a wide-character string, prepend the decorator name with the `w` letter (e.g. use `wxml_decor` instead of `xml_decor`). Also, for each decorator there is a generator function that accepts the character type as a template parameter; the function is named similarly to the decorator prepended with the `make_` prefix (e.g. `make_xml_decor`).]
  339. [section:xml XML character decorator]
  340. #include <``[boost_log_expressions_formatters_xml_decorator_hpp]``>
  341. This decorator replaces XML special characters (&, <, >, \" and \') with the corresponding tokens (`&amp;`, `&lt;`, `&gt;`, `&quot;` and `&apos;`, correspondingly). The usage is as follows:
  342. xml_sink->set_formatter
  343. (
  344. // Apply the decoration to the whole formatted record
  345. expr::stream << expr::xml_decor
  346. [
  347. expr::stream << expr::message
  348. ]
  349. );
  350. Since character decorators are yet another kind of formatters, it's fine to use them in other contexts where formatters are appropriate. For example, this is also a valid example:
  351. xml_sink->set_formatter
  352. (
  353. expr::format("<message>%1%: %2%</message>")
  354. % expr::attr< unsigned int >("LineID")
  355. % expr::xml_decor[ expr::stream << expr::message ]; // Only decorate the message text
  356. );
  357. There is an example of the library set up for logging into an XML file, see [@boost:/libs/log/example/doc/sinks_xml_file.cpp here].
  358. [endsect]
  359. [section:csv CSV character decorator]
  360. #include <``[boost_log_expressions_formatters_csv_decorator_hpp]``>
  361. This decorator allows to ensure that the resulting string conforms to the [@http://en.wikipedia.org/wiki/Comma-separated_values CSV] format requirements. In particular, it duplicates the quote characters in the formatted string.
  362. csv_sink->set_formatter
  363. (
  364. expr::stream
  365. << expr::attr< unsigned int >("LineID") << ","
  366. << expr::csv_decor[ expr::stream << expr::attr< std::string >("Tag") ] << ","
  367. << expr::csv_decor[ expr::stream << expr::message ]
  368. );
  369. [endsect]
  370. [section:c C-style character decorators]
  371. #include <``[boost_log_expressions_formatters_c_decorator_hpp]``>
  372. The header defines two character decorators: `c_decor` and `c_ascii_decor`. The first one replaces the following characters with their escaped counterparts: \\ (backslash, 0x5c), \\a (bell character, 0x07), \\b (backspace, 0x08), \\f (formfeed, 0x0c), \\n (newline, 0x0a), \\r (carriage return, 0x0d), \\t (horizontal tabulation, 0x09), \\v (vertical tabulation, 0x0b), \' (apostroph, 0x27), \" (quote, 0x22), ? (question mark, 0x3f). The `c_ascii_decor` decorator does the same but also replaces all other non-printable and non-ASCII characters with escaped hexadecimal character codes in C notation (e.g. "\\x8c"). The usage is similar to other character decorators:
  373. sink->set_formatter
  374. (
  375. expr::stream
  376. << expr::attr< unsigned int >("LineID") << ": ["
  377. << expr::c_decor[ expr::stream << expr::attr< std::string >("Tag") ] << "] "
  378. << expr::c_ascii_decor[ expr::stream << expr::message ]
  379. );
  380. [endsect]
  381. [section:char General character decorator]
  382. #include <``[boost_log_expressions_formatters_char_decorator_hpp]``>
  383. This decorator allows the user to define his own character replacement mapping in one of the two forms. The first form is a range of `std::pair`s of strings (which can be C-style strings or ranges of characters, including `std::string`s). The strings in the `first` elements of pairs will be replaced with the `second` elements of the corresponding pair.
  384. std::array< std::pair< const char*, const char* >, 3 > shell_escapes =
  385. {
  386. { "\"", "\\\"" },
  387. { "'", "\\'" },
  388. { "$", "\\$" }
  389. };
  390. sink->set_formatter
  391. (
  392. expr::stream << expr::char_decor(shell_escapes)
  393. [
  394. expr::stream << expr::message
  395. ]
  396. );
  397. The second form is two same-sized sequences of strings; the first containing the search patterns and the second - the corresponding replacements.
  398. std::array< const char*, 3 > shell_patterns =
  399. {
  400. "\"", "'", "$"
  401. };
  402. std::array< const char*, 3 > shell_replacements =
  403. {
  404. "\\\"", "\\'", "\\$"
  405. };
  406. sink->set_formatter
  407. (
  408. expr::stream << expr::char_decor(shell_patterns, shell_replacements)
  409. [
  410. expr::stream << expr::message
  411. ]
  412. );
  413. In both cases the patterns are not interpreted and are sought in the formatted characters in the original form.
  414. [endsect]
  415. [section:max_size String length limiting decorator]
  416. #include <``[boost_log_expressions_formatters_max_size_decorator_hpp]``>
  417. Sometimes it can be useful to be able to limit the size of the output of a formatter or its part. For example, the limit might be imposed by the sink or the required output format. The `max_size_decor` decorator allows to enforce such limit. Let's see a simple example:
  418. sink->set_formatter
  419. (
  420. expr::stream << expr::max_size_decor< char >(20)
  421. [
  422. expr::stream << expr::message
  423. ]
  424. );
  425. [note The explicit template parameter for `max_size_decor` specifies the character type that is used by formatter. In this example the string produced by the formatter contains characters of type `char`, hence the template parameter.]
  426. In this example the decorator limits the log message to no more than 20 [@https://en.wikipedia.org/wiki/Character_encoding#Terminology code units] of type `char` and removes the rest from the output. So if we had a log record like this:
  427. BOOST_LOG(lg) << "The quick brown fox jumps over the lazy dog";
  428. the resulting output would look like this:
  429. [pre
  430. The quick brown fox
  431. ]
  432. However, looking at this output in a log file it is unclear whether the original output contained anything else. One might want to indicate the fact of message truncation, should one occur. For that purpose the decorator allows to specify an overflow marker that will be placed at the end of the truncated output, if the truncation took place. We can modify the above example like this:
  433. sink->set_formatter
  434. (
  435. expr::stream << expr::max_size_decor(20, ">>>")
  436. [
  437. expr::stream << expr::message
  438. ]
  439. );
  440. [tip The formatter character type is deduced from the character type of the overflow marker, so it can be omitted.]
  441. Now our log record will look like this in the output:
  442. [pre
  443. The quick brown f>>>
  444. ]
  445. This output makes it more obvious that there was more to the original message. Note also that the length of the output is still 20 characters; the marker replaced the last characters of the truncated output.
  446. [tip For the character truncation and marker positioning to work correctly in multibyte encodings, it is important that the locale used by the formatter is set up properly. In particular, the `std::codecvt` facet in the locale must correctly recognize multibyte sequences corresponding to a single character in the output. One can use __boost_locale__ to generate the locale and then install it in the sink frontend by calling `imbue` (see [class_sinks_basic_formatting_sink_frontend] for reference). If the output character type is `wchar_t`, `char16_t` or `char32_t` the library assumes that the output is encoded in UTF-16 or UTF-32, depending on the size of the character type. Because the truncation might occur in the middle of a multi-unit character, truncated output produced by the decorator can be slightly shorter than the specified limit sometimes.]
  447. As with any other formatter, `max_size_decor` can participate in more complex formatting expressions and limit length of only part of the message.
  448. sink->set_formatter
  449. (
  450. expr::stream
  451. << expr::format_date_time("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << " ["
  452. << expr::max_size_decor(20, ">>>")
  453. [
  454. expr::stream << expr::message
  455. ]
  456. << "]"
  457. );
  458. The above formatter can produce output like this:
  459. [pre
  460. 2016-08-10 00:36:44.028473 \[The quick brown f>>>\]
  461. ]
  462. [endsect]
  463. [endsect]
  464. [endsect]
  465. [endsect]