BDE 4.39.x Production Release
Loading...
Searching...
No Matches
ball_recordstringformatter.h
Go to the documentation of this file.
1/// @file ball_recordstringformatter.h
2///
3/// The content of this file has been pre-processed for Doxygen.
4///
5
6
7// ball_recordstringformatter.h -*-C++-*-
8#ifndef INCLUDED_BALL_RECORDSTRINGFORMATTER
9#define INCLUDED_BALL_RECORDSTRINGFORMATTER
10
11#include <bsls_ident.h>
12BSLS_IDENT("$Id: $")
13
14/// @defgroup ball_recordstringformatter ball_recordstringformatter
15/// @brief Provide a record formatter that uses a `printf`-style format spec.
16/// @addtogroup bal
17/// @{
18/// @addtogroup ball
19/// @{
20/// @addtogroup ball_recordstringformatter
21/// @{
22///
23/// <h1> Outline </h1>
24/// * <a href="#ball_recordstringformatter-purpose"> Purpose</a>
25/// * <a href="#ball_recordstringformatter-classes"> Classes </a>
26/// * <a href="#ball_recordstringformatter-description"> Description </a>
27/// * <a href="#ball_recordstringformatter-record-format-specification"> Record Format Specification </a>
28/// * <a href="#ball_recordstringformatter-log-record-attributes-rendering-details"> Log Record Attributes Rendering Details </a>
29/// * <a href="#ball_recordstringformatter-usage"> Usage </a>
30///
31/// # Purpose {#ball_recordstringformatter-purpose}
32/// Provide a record formatter that uses a `printf`-style format spec.
33///
34/// # Classes {#ball_recordstringformatter-classes}
35///
36/// - ball::RecordStringFormatter: `printf`-style formatter for log records
37///
38/// @see ball_record, ball_recordattributes
39///
40/// # Description {#ball_recordstringformatter-description}
41/// This component provides a value-semantic function-object class,
42/// `ball::RecordStringFormatter`, that is used to format log records according
43/// to a `printf`-style format specification (see "Record Format Specification"
44/// below). A format specification and a timestamp offset (in the form of a
45/// `bdlt::DatetimeInterval`) are optionally supplied upon construction of a
46/// `ball::RecordStringFormatter` object (or simply "record formatter"). If a
47/// format specification is not supplied, a default one (defined below) is used.
48/// If a timestamp offset is not supplied, it defaults to 0. Both the format
49/// specification and timestamp offset of a record formatter can be modified
50/// following construction.
51///
52/// An overloaded `operator()` is defined for `ball::RecordStringFormatter` that
53/// takes a `ball::Record` and an `bsl::ostream` as arguments. This method
54/// formats the given record according to the format specification of the record
55/// formatter and outputs the result to the given stream. Additionally, each
56/// timestamp indicated in the format specification is biased by the timestamp
57/// offset of the record formatter prior to outputting it to the stream. This
58/// facilitates the logging of records in local time, if desired, in the event
59/// that the timestamp attribute of records are in UTC.
60///
61/// ## Record Format Specification {#ball_recordstringformatter-record-format-specification}
62///
63///
64/// The following table lists the `printf`-style (`%`-prefixed) conversion
65/// specifications, including their expansions, that are recognized within the
66/// format specification of a record formatter:
67/// @code
68/// %d - timestamp in 'DDMonYYYY_HH:MM:SS.mmm' format (27AUG2007_16:09:46.161)
69/// %D - timestamp in 'DDMonYYYY_HH:MM:SS.mmmuuu' format
70/// (27AUG2007_16:09:46.161324)
71/// %dtz - timestamp in 'DDMonYYYY_HH:MM:SS.mmm(+|-)HHMM' format
72/// (27AUG2007_16:09:46.161+0000)
73/// %Dtz - timestamp in 'DDMonYYYY_HH:MM:SS.mmmuuu(+|-)HHMM' format
74/// (27AUG2007_16:09:46.161324+0000)
75/// %i - timestamp in ISO 8601 format (without the millisecond or microsecond
76/// fields)
77/// %I - timestamp in ISO 8601 format (*with* the millisecond field)
78/// %O - timestamp in ISO 8601 format (*with* the millisecond and microsecond
79/// fields)
80/// %p - process Id
81/// %t - thread Id
82/// %T - thread Id in hex
83/// %k - kernel thread Id
84/// %K - kernel thread Id in hex
85/// %s - severity
86/// %f - filename (as provided by '__FILE__')
87/// %F - filename abbreviated (basename of '__FILE__' only)
88/// %l - line number (as provided by '__LINE__')
89/// %c - category name
90/// %m - log message
91/// %x - log message with non-printable characters in hex
92/// %X - log message entirely in hex
93/// %u - user-defined fields
94/// %% - single '%' character
95/// %A - log all the attributes of the record
96/// %a - log only those attributes not already logged by the %a[name] or
97/// %av[name] specifier(s)
98/// %a[name] - log an attribute with the specified 'name' as "name=value",
99/// log nothing if the attribute with the specified 'name' is not found
100/// %av[name] - log only the value of an attribute with the specified 'name',
101/// log nothing if the attribute with the specified 'name' is not found
102/// @endcode
103/// (Note that `"%F"` is used to indicate the shortened form of `__FILE__`
104/// rather than `"%f"` because `"%f"` was given its current interpretation in
105/// an earlier version of this component.)
106///
107/// In addition, the following '\'-escape sequences are interpolated in the
108/// formatted output as indicated when they occur in the format specification:
109/// @code
110/// \n - newline character
111/// \t - tab character
112/// \\ - single '\' character
113/// @endcode
114/// Any other text included in the format specification of the record formatter
115/// is output verbatim.
116///
117/// When not supplied at construction, the default format specification of a
118/// record formatter is:
119/// @code
120/// "\n%d %p:%t %s %f:%l %c %m %u\n"
121/// @endcode
122/// A default-formatted record having no user-defined fields will have the
123/// following appearance:
124/// @code
125/// 27AUG2007_16:09:46.161 2040:1 WARN subdir/process.cpp:542 FOO.BAR.BAZ <text>
126/// @endcode
127///
128/// ## Log Record Attributes Rendering Details {#ball_recordstringformatter-log-record-attributes-rendering-details}
129///
130///
131/// Log record attributes are rendered as space-separated `name="value"` pairs
132/// (for example: mylibrary.username="mbloomberg"). Note that attribute names
133/// are *not* quoted, whereas attribute values, if they are strings, are
134/// *always* quoted.
135///
136/// ## Usage {#ball_recordstringformatter-usage}
137///
138///
139/// The following snippets of code illustrate how to use an instance of
140/// `ball::RecordStringFormatter` to format log records.
141///
142/// First we instantiate a record formatter with an explicit format
143/// specification (but we accept the default timestamp offset since it will not
144/// be used in this example):
145/// @code
146/// ball::RecordStringFormatter formatter("%t: %m\n");
147/// @endcode
148/// The chosen format specification indicates that, when a record is formatted
149/// using `formatter`, the thread Id attribute of the record will be output
150/// followed by the message attribute of the record.
151///
152/// Next we create a default `ball::Record` and set the thread Id and message
153/// attributes of the record to dummy values:
154/// @code
155/// ball::Record record;
156///
157/// record.fixedFields().setThreadID(6);
158/// record.fixedFields().setMessage("Hello, World!");
159/// @endcode
160/// The following "invocation" of the `formatter` function object formats
161/// `record` to `bsl::cout` according to the format specification supplied at
162/// construction:
163/// @code
164/// formatter(bsl::cout, record);
165/// @endcode
166/// As a result of this call, the following is printed to `stdout`:
167/// @code
168/// 6: Hello, World!
169/// @endcode
170/// @}
171/** @} */
172/** @} */
173
174/** @addtogroup bal
175 * @{
176 */
177/** @addtogroup ball
178 * @{
179 */
180/** @addtogroup ball_recordstringformatter
181 * @{
182 */
183
184#include <balscm_version.h>
185
188
190
191#include <bslma_allocator.h>
193
195
196#include <bsl_functional.h>
197#include <bsl_iosfwd.h>
198#include <bsl_string.h>
199#include <bsl_string_view.h>
200#include <bsl_set.h>
201#include <bsl_vector.h>
202
203
204namespace ball {
205
206class Record;
207
208 // ===========================
209 // class RecordStringFormatter
210 // ===========================
211
212/// This class provides a value-semantic log record formatter that holds a
213/// `printf`-style format specification and a timestamp offset. The
214/// overloaded `operator()` provided by the class formats a given record
215/// according to the format specification and outputs the formatted result
216/// to a given stream. The timestamp offset of the record formatter is
217/// added to each timestamp that is output to the stream.
218///
219/// See @ref ball_recordstringformatter
221
222 // PRIVATE TYPES
223
224 /// `FieldStringFormatter` is an alias for a functional object that
225 /// render fields provided by a `ball::Record` to a string.
226 typedef bsl::function<void(bsl::string *, const Record&)>
227 FieldStringFormatter;
228
229 /// `FieldStringFormatters` is an alias for a vector of the
230 /// `FieldStringFormatter` objects.
232
233 /// `SkipAttributes` is an alias for a set of keys of attributes that
234 /// should not be printed as part of a `"%a"` format specifier.
236
237 public:
238 // TYPES
240
241 private:
242 // DATA
243 bsl::string d_formatSpec; // 'printf'-style format spec.
244 FieldStringFormatters d_fieldFormatters; // field formatter collection
245 SkipAttributes d_skipAttributes; // set of skipped attributes
246 bdlt::DatetimeInterval d_timestampOffset; // offset added to timestamps
247
248 // PRIVATE MANIPULATORS
249
250 /// Parse the format specification.
251 void parseFormatSpecification();
252
253 public:
254 // TRAITS
257
258 // PUBLIC CONSTANTS
259
260 /// The default log format specification used by `RecordStringFormatter`.
261 static const char *k_DEFAULT_FORMAT;
262
263 /// A simple standard record format that renders `ball::Attribute` values in the formatted output.
264 ///
265 /// \note Note that this format is recommended over the
266 /// default format, `k_DEFAULT_FORMAT`, for most applications (the default
267 /// format is currently maintained for backwards compatibility).
268 static const char *k_BASIC_ATTRIBUTE_FORMAT;
269
270 // CLASS METHODS
271
272 /// This class method configures a formatter for the "text" scheme using
273 /// the specified `format` and `formatOptions` and if successful loads it
274 /// into the specified `output` and returns zero. In case configuration
275 /// fails a non-zero value is returned and `output` is loaded with a
276 /// string formatter of the default format configuration
277 /// @code
278 /// "\n%d %p:%t %s %f:%l %c %m %u\n"
279 /// @endcode
283 const RecordFormatterOptions& formatOptions);
284
285 // CREATORS
286
287 /// Create a record formatter having a default format specification and
288 /// a timestamp offset of 0. Optionally specify an `allocator` (e.g.,
289 /// the address of a `bslma::Allocator` object) to supply memory. If
290 /// `basicAllocator` is not supplied or 0, the currently installed
291 /// default allocator is used. The default format specification is:
292 /// @code
293 /// "\n%d %p:%t %s %f:%l %c %m %u\n"
294 /// @endcode
296 const allocator_type& allocator = allocator_type());
298 bslma::Allocator *basicallocator);
299
300 /// Create a record formatter having the specified `format`
301 /// specification and a timestamp offset of 0. Optionally specify an
302 /// `allocator` (e.g., the address of a `bslma::Allocator` object) to
303 /// supply memory. If `basicAllocator` is not supplied or 0, the
304 /// currently installed default allocator is used.
306 const char *format,
307 const allocator_type& allocator = allocator_type());
309 bslma::Allocator *basicAllocator);
312 const allocator_type& allocator = allocator_type());
313
314 /// Create a record formatter having a default format specification and
315 /// the specified timestamp `offset`. Optionally specify an `allocator`
316 /// (e.g., the address of a `bslma::Allocator` object) to supply memory;
317 /// otherwise, the default allocator is used. The default format
318 /// specification is:
319 /// @code
320 /// "\n%d %p:%t %s %f:%l %c %m %u\n"
321 /// @endcode
322 ///
323 /// @deprecated Use a constructor taking `publishInLocalTime` instead.
325 const bdlt::DatetimeInterval& offset,
326 const allocator_type& allocator = allocator_type());
327
328 /// Create a record formatter having a default format specification, and
329 /// if the specified `publishInLocalTime` flag is `true`, format the
330 /// timestamp of each logged record in the local time of the current
331 /// task, and format the timestamp in UTC otherwise. Optionally specify
332 /// an `allocator` (e.g., the address of a `bslma::Allocator` object) to
333 /// supply memory; otherwise, the default allocator is used. The
334 /// default format specification is:
335 /// @code
336 /// "\n%d %p:%t %s %f:%l %c %m %u\n"
337 /// @endcode
338 ///
339 /// \note Note that local time offsets are calculated for the timestamp of
340 /// each formatted record and so track transitions into and out of
341 /// Daylight Saving Time.
343 bool publishInLocalTime,
344 const allocator_type& allocator = allocator_type());
345
346 /// Create a record formatter having the specified `format`
347 /// specification and the specified timestamp `offset`. Optionally
348 /// specify an `allocator` (e.g., the address of a `bslma::Allocator`
349 /// object) to supply memory; otherwise, the default allocator is used.
350 ///
351 /// @deprecated Use a constructor taking `publishInLocalTime` instead.
353 const char *format,
354 const bdlt::DatetimeInterval& offset,
355 const allocator_type& allocator = allocator_type());
356
357 /// Create a record formatter having the specified `format`
358 /// specification, and if the specified `publishInLocalTime` flag is
359 /// `true`, format the timestamp of each log in the local time of the
360 /// current task, and format the timestamp in UTC otherwise. Optionally
361 /// specify an `allocator` (e.g., the address of a `bslma::Allocator`
362 /// object) to supply memory; otherwise, the default allocator is used.
363 ///
364 /// \note Note that local time offsets are calculated for the timestamp of
365 /// each formatted record and so track transitions into and out of
366 /// Daylight Saving Time.
368 bool publishInLocalTime,
369 const allocator_type& allocator = allocator_type());
370
371 /// Create a record formatter initialized to the value of the specified
372 /// `original` record formatter. Optionally specify an `allocator`
373 /// (e.g., the address of a `bslma::Allocator` object) to supply memory;
374 /// otherwise, the default allocator is used.
376 const RecordStringFormatter& original,
377 const allocator_type& allocator = allocator_type());
378
379 /// Destroy this object.
381
382 // MANIPULATORS
383
384 /// Assign to this record formatter the value of the specified `rhs`
385 /// record formatter.
387
388 /// Disable adjust of the timestamp attribute of to the current local
389 /// time by this file observer. This method has no effect if adjustment
390 /// to the current local time is not enabled.
392
393 /// Enable adjustment of the timestamp attribute to the current local
394 /// time. This method has no effect if adjustment to the current local
395 /// time is already enabled.
397
398 /// Set the format specification of this record formatter to the
399 /// specified `format`.
400 void setFormat(const char *format);
401
402 /// Set the timestamp offset of this record formatter to the specified
403 /// `offset`.
404 ///
405 /// @deprecated Use @ref enablePublishInLocalTime instead.
406 void setTimestampOffset(const bdlt::DatetimeInterval& offset);
407
408 // ACCESSORS
409
410 /// Format the specified `record` according to the format specification
411 /// of this record formatter and output the result to the specified
412 /// `stream`. The timestamp offset of this record formatter is added to
413 /// each timestamp that is output to `stream`.
414 void operator()(bsl::ostream& stream, const Record& record) const;
415
416 /// Return the format specification of this record formatter.
417 const char *format() const;
418
419 /// Return `true` if this formatter adjusts the timestamp attribute to
420 /// the current local time, and `false` otherwise.
422
423 /// Return a reference to the non-modifiable timestamp offset of this
424 /// record formatter.
425 ///
426 /// @deprecated Use @ref isPublishInLocalTimeEnabled instead.
428
429 // Aspects
430
431 /// Return the allocator used by this object to supply memory.
432 ///
433 /// \note Note that if no allocator was supplied at construction the default
434 /// allocator in effect at construction is used.
436};
437
438// FREE OPERATORS
439
440/// Return `true` if the specified `lhs` and `rhs` record formatters have
441/// the same value, and `false` otherwise. Two record formatters have the
442/// same value if they have the same format specification and the same
443/// timestamp offset.
444bool operator==(const RecordStringFormatter& lhs,
445 const RecordStringFormatter& rhs);
446
447/// Return `true` if the specified `lhs` and `rhs` record formatters do not
448/// have the same value, and `false` otherwise. Two record formatters
449/// differ in value if their format specifications differ or their timestamp
450/// offsets differ.
451bool operator!=(const RecordStringFormatter& lhs,
452 const RecordStringFormatter& rhs);
453
454/// Write the specified `rhs` record formatter to the specified `output`
455/// stream in some reasonable (single-line) format and return a reference
456/// to the modifiable `stream`.
457bsl::ostream& operator<<(bsl::ostream& output,
458 const RecordStringFormatter& rhs);
459
460// ============================================================================
461// INLINE DEFINITIONS
462// ============================================================================
463
464 // ---------------------------
465 // class RecordStringFormatter
466 // ---------------------------
467
468// MANIPULATORS
469inline
470void RecordStringFormatter::setFormat(const char *format)
471{
472 d_formatSpec = format;
473 parseFormatSpecification();
474}
475
476inline
478 const bdlt::DatetimeInterval& offset)
479{
480 d_timestampOffset = offset;
481}
482
483// ACCESSORS
484inline
486{
487 return d_formatSpec.c_str();
488}
489
490inline
493{
494 return d_timestampOffset;
495}
496
497 // Aspects
498
499inline
502{
503 return d_formatSpec.get_allocator();
504}
505
506} // close package namespace
507
508// FREE OPERATORS
509inline
510bool ball::operator!=(const RecordStringFormatter& lhs,
511 const RecordStringFormatter& rhs)
512{
513 return !(lhs == rhs);
514}
515
516
517
518#endif
519
520// ----------------------------------------------------------------------------
521// Copyright 2015 Bloomberg Finance L.P.
522//
523// Licensed under the Apache License, Version 2.0 (the "License");
524// you may not use this file except in compliance with the License.
525// You may obtain a copy of the License at
526//
527// http://www.apache.org/licenses/LICENSE-2.0
528//
529// Unless required by applicable law or agreed to in writing, software
530// distributed under the License is distributed on an "AS IS" BASIS,
531// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
532// See the License for the specific language governing permissions and
533// limitations under the License.
534// ----------------------------- END-OF-FILE ----------------------------------
535
536/** @} */
537/** @} */
538/** @} */
Definition ball_recordformatteroptions.h:112
Definition ball_recordstringformatter.h:220
bsl::allocator< char > allocator_type
Definition ball_recordstringformatter.h:239
BSLMF_NESTED_TRAIT_DECLARATION(RecordStringFormatter, bslma::UsesBslmaAllocator)
const char * format() const
Return the format specification of this record formatter.
Definition ball_recordstringformatter.h:485
RecordStringFormatter(const bsl::string_view &format, const allocator_type &allocator=allocator_type())
RecordStringFormatter(const char *format, bool publishInLocalTime, const allocator_type &allocator=allocator_type())
RecordStringFormatter(const char *format, const bdlt::DatetimeInterval &offset, const allocator_type &allocator=allocator_type())
void operator()(bsl::ostream &stream, const Record &record) const
RecordStringFormatter(const char *format, const allocator_type &allocator=allocator_type())
void setFormat(const char *format)
Definition ball_recordstringformatter.h:470
RecordStringFormatter & operator=(const RecordStringFormatter &rhs)
RecordStringFormatter(const allocator_type &allocator=allocator_type())
static const char * k_BASIC_ATTRIBUTE_FORMAT
Definition ball_recordstringformatter.h:268
const bdlt::DatetimeInterval & timestampOffset() const
Definition ball_recordstringformatter.h:492
static int loadTextSchemeFormatter(RecordFormatterFunctor::Type *output, const bsl::string_view &format, const RecordFormatterOptions &formatOptions)
RecordStringFormatter(bool publishInLocalTime, const allocator_type &allocator=allocator_type())
RecordStringFormatter(const bdlt::DatetimeInterval &offset, const allocator_type &allocator=allocator_type())
RecordStringFormatter(const RecordStringFormatter &original, const allocator_type &allocator=allocator_type())
allocator_type get_allocator() const
Definition ball_recordstringformatter.h:501
bool isPublishInLocalTimeEnabled() const
RecordStringFormatter(bslma::Allocator *basicallocator)
~RecordStringFormatter()=default
Destroy this object.
static const char * k_DEFAULT_FORMAT
The default log format specification used by RecordStringFormatter.
Definition ball_recordstringformatter.h:261
void setTimestampOffset(const bdlt::DatetimeInterval &offset)
Definition ball_recordstringformatter.h:477
RecordStringFormatter(const char *format, bslma::Allocator *basicAllocator)
Definition ball_record.h:176
Definition bdlt_datetimeinterval.h:201
Definition bslma_bslallocator.h:588
Definition bslstl_stringview.h:471
Definition bslstl_string.h:1252
const CHAR_TYPE * c_str() const BSLS_KEYWORD_NOEXCEPT
Definition bslstl_string.h:7405
allocator_type get_allocator() const BSLS_KEYWORD_NOEXCEPT
Return the allocator used by this string to supply memory.
Definition bslstl_string.h:7423
Forward declaration.
Definition bslstl_function.h:946
Definition bslstl_set.h:691
Definition bslstl_vector.h:1120
Definition bslma_allocator.h:545
#define BSLS_IDENT(str)
BSLS_IDENT() - insert string into .comment binary segment (if supported)
Definition bsls_ident.h:238
Definition ball_administration.h:214
bsl::ostream & operator<<(bsl::ostream &output, const Attribute &attribute)
bool operator!=(const Attribute &lhs, const Attribute &rhs)
Definition bslma_usesbslmaallocator.h:344