xref: /minix3/external/bsd/kyua-cli/dist/utils/logging/operations.cpp (revision 11be35a165022172ed3cea20f2b5df0307540b0e)
1*11be35a1SLionel Sambuc // Copyright 2011 Google Inc.
2*11be35a1SLionel Sambuc // All rights reserved.
3*11be35a1SLionel Sambuc //
4*11be35a1SLionel Sambuc // Redistribution and use in source and binary forms, with or without
5*11be35a1SLionel Sambuc // modification, are permitted provided that the following conditions are
6*11be35a1SLionel Sambuc // met:
7*11be35a1SLionel Sambuc //
8*11be35a1SLionel Sambuc // * Redistributions of source code must retain the above copyright
9*11be35a1SLionel Sambuc //   notice, this list of conditions and the following disclaimer.
10*11be35a1SLionel Sambuc // * Redistributions in binary form must reproduce the above copyright
11*11be35a1SLionel Sambuc //   notice, this list of conditions and the following disclaimer in the
12*11be35a1SLionel Sambuc //   documentation and/or other materials provided with the distribution.
13*11be35a1SLionel Sambuc // * Neither the name of Google Inc. nor the names of its contributors
14*11be35a1SLionel Sambuc //   may be used to endorse or promote products derived from this software
15*11be35a1SLionel Sambuc //   without specific prior written permission.
16*11be35a1SLionel Sambuc //
17*11be35a1SLionel Sambuc // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18*11be35a1SLionel Sambuc // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19*11be35a1SLionel Sambuc // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20*11be35a1SLionel Sambuc // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21*11be35a1SLionel Sambuc // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22*11be35a1SLionel Sambuc // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23*11be35a1SLionel Sambuc // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24*11be35a1SLionel Sambuc // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25*11be35a1SLionel Sambuc // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26*11be35a1SLionel Sambuc // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27*11be35a1SLionel Sambuc // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*11be35a1SLionel Sambuc 
29*11be35a1SLionel Sambuc #include "utils/logging/operations.hpp"
30*11be35a1SLionel Sambuc 
31*11be35a1SLionel Sambuc extern "C" {
32*11be35a1SLionel Sambuc #include <unistd.h>
33*11be35a1SLionel Sambuc }
34*11be35a1SLionel Sambuc 
35*11be35a1SLionel Sambuc #include <fstream>
36*11be35a1SLionel Sambuc #include <stdexcept>
37*11be35a1SLionel Sambuc #include <string>
38*11be35a1SLionel Sambuc #include <utility>
39*11be35a1SLionel Sambuc #include <vector>
40*11be35a1SLionel Sambuc 
41*11be35a1SLionel Sambuc #include "utils/datetime.hpp"
42*11be35a1SLionel Sambuc #include "utils/format/macros.hpp"
43*11be35a1SLionel Sambuc #include "utils/optional.ipp"
44*11be35a1SLionel Sambuc #include "utils/sanity.hpp"
45*11be35a1SLionel Sambuc 
46*11be35a1SLionel Sambuc namespace datetime = utils::datetime;
47*11be35a1SLionel Sambuc namespace fs = utils::fs;
48*11be35a1SLionel Sambuc namespace logging = utils::logging;
49*11be35a1SLionel Sambuc 
50*11be35a1SLionel Sambuc using utils::none;
51*11be35a1SLionel Sambuc using utils::optional;
52*11be35a1SLionel Sambuc 
53*11be35a1SLionel Sambuc 
54*11be35a1SLionel Sambuc /// The general idea for the application-wide logging goes like this:
55*11be35a1SLionel Sambuc ///
56*11be35a1SLionel Sambuc /// 1. The application starts.  Logging is initialized to capture _all_ log
57*11be35a1SLionel Sambuc /// messages into memory regardless of their level by issuing a call to the
58*11be35a1SLionel Sambuc /// set_inmemory() function.
59*11be35a1SLionel Sambuc ///
60*11be35a1SLionel Sambuc /// 2. The application offers the user a way to select the logging level and a
61*11be35a1SLionel Sambuc /// file into which to store the log.
62*11be35a1SLionel Sambuc ///
63*11be35a1SLionel Sambuc /// 3. The application calls set_persistency providing a new log level and a log
64*11be35a1SLionel Sambuc /// file.  This must be done as early as possible, to minimize the chances of an
65*11be35a1SLionel Sambuc /// early crash not capturing any logs.
66*11be35a1SLionel Sambuc ///
67*11be35a1SLionel Sambuc /// 4. At this point, any log messages stored into memory are flushed to disk
68*11be35a1SLionel Sambuc /// respecting the provided log level.
69*11be35a1SLionel Sambuc ///
70*11be35a1SLionel Sambuc /// 5. The internal state of the logging module is updated to only capture
71*11be35a1SLionel Sambuc /// messages that are of the provided log level (or below) and is configured to
72*11be35a1SLionel Sambuc /// directly send messages to disk.
73*11be35a1SLionel Sambuc ///
74*11be35a1SLionel Sambuc /// The call to set_inmemory() should only be performed by the user-facing
75*11be35a1SLionel Sambuc /// application.  Tests should skip this call so that the logging messages go to
76*11be35a1SLionel Sambuc /// stderr by default, thus generating a useful log to debug the tests.
77*11be35a1SLionel Sambuc 
78*11be35a1SLionel Sambuc 
79*11be35a1SLionel Sambuc namespace {
80*11be35a1SLionel Sambuc 
81*11be35a1SLionel Sambuc 
82*11be35a1SLionel Sambuc /// Current log level.
83*11be35a1SLionel Sambuc static logging::level log_level = logging::level_debug;
84*11be35a1SLionel Sambuc 
85*11be35a1SLionel Sambuc 
86*11be35a1SLionel Sambuc /// Indicates whether set_persistency() will be called automatically or not.
87*11be35a1SLionel Sambuc static bool auto_set_persistency = true;
88*11be35a1SLionel Sambuc 
89*11be35a1SLionel Sambuc 
90*11be35a1SLionel Sambuc /// First time recorded by the logging module.
91*11be35a1SLionel Sambuc static optional< datetime::timestamp > first_timestamp = none;
92*11be35a1SLionel Sambuc 
93*11be35a1SLionel Sambuc 
94*11be35a1SLionel Sambuc /// In-memory record of log entries before persistency is enabled.
95*11be35a1SLionel Sambuc static std::vector< std::pair< logging::level, std::string > > backlog;
96*11be35a1SLionel Sambuc 
97*11be35a1SLionel Sambuc 
98*11be35a1SLionel Sambuc /// Stream to the currently open log file.
99*11be35a1SLionel Sambuc static std::auto_ptr< std::ofstream > logfile;
100*11be35a1SLionel Sambuc 
101*11be35a1SLionel Sambuc 
102*11be35a1SLionel Sambuc /// Constant string to strftime to format timestamps.
103*11be35a1SLionel Sambuc static const char* timestamp_format = "%Y%m%d-%H%M%S";
104*11be35a1SLionel Sambuc 
105*11be35a1SLionel Sambuc 
106*11be35a1SLionel Sambuc /// Converts a level to a printable character.
107*11be35a1SLionel Sambuc ///
108*11be35a1SLionel Sambuc /// \param level The level to convert.
109*11be35a1SLionel Sambuc ///
110*11be35a1SLionel Sambuc /// \return The printable character, to be used in log messages.
111*11be35a1SLionel Sambuc static char
level_to_char(const logging::level level)112*11be35a1SLionel Sambuc level_to_char(const logging::level level)
113*11be35a1SLionel Sambuc {
114*11be35a1SLionel Sambuc     switch (level) {
115*11be35a1SLionel Sambuc     case logging::level_error: return 'E';
116*11be35a1SLionel Sambuc     case logging::level_warning: return 'W';
117*11be35a1SLionel Sambuc     case logging::level_info: return 'I';
118*11be35a1SLionel Sambuc     case logging::level_debug: return 'D';
119*11be35a1SLionel Sambuc     default: UNREACHABLE;
120*11be35a1SLionel Sambuc     }
121*11be35a1SLionel Sambuc }
122*11be35a1SLionel Sambuc 
123*11be35a1SLionel Sambuc 
124*11be35a1SLionel Sambuc }  // anonymous namespace
125*11be35a1SLionel Sambuc 
126*11be35a1SLionel Sambuc 
127*11be35a1SLionel Sambuc /// Generates a standard log name.
128*11be35a1SLionel Sambuc ///
129*11be35a1SLionel Sambuc /// This always adds the same timestamp to the log name for a particular run.
130*11be35a1SLionel Sambuc /// Also, the timestamp added to the file name corresponds to the first
131*11be35a1SLionel Sambuc /// timestamp recorded by the module; it does not necessarily contain the
132*11be35a1SLionel Sambuc /// current value of "now".
133*11be35a1SLionel Sambuc ///
134*11be35a1SLionel Sambuc /// \param logdir The path to the directory in which to place the log.
135*11be35a1SLionel Sambuc /// \param progname The name of the program that is generating the log.
136*11be35a1SLionel Sambuc fs::path
generate_log_name(const fs::path & logdir,const std::string & progname)137*11be35a1SLionel Sambuc logging::generate_log_name(const fs::path& logdir, const std::string& progname)
138*11be35a1SLionel Sambuc {
139*11be35a1SLionel Sambuc     if (!first_timestamp)
140*11be35a1SLionel Sambuc         first_timestamp = datetime::timestamp::now();
141*11be35a1SLionel Sambuc     // Update doc/troubleshooting.texi if you change the name format.
142*11be35a1SLionel Sambuc     return logdir / (F("%s.%s.log") % progname %
143*11be35a1SLionel Sambuc                      first_timestamp.get().strftime(timestamp_format));
144*11be35a1SLionel Sambuc }
145*11be35a1SLionel Sambuc 
146*11be35a1SLionel Sambuc 
147*11be35a1SLionel Sambuc /// Logs an entry to the log file.
148*11be35a1SLionel Sambuc ///
149*11be35a1SLionel Sambuc /// If the log is not yet set to persistent mode, the entry is recorded in the
150*11be35a1SLionel Sambuc /// in-memory backlog.  Otherwise, it is just written to disk.
151*11be35a1SLionel Sambuc ///
152*11be35a1SLionel Sambuc /// \param message_level The level of the entry.
153*11be35a1SLionel Sambuc /// \param file The file from which the log message is generated.
154*11be35a1SLionel Sambuc /// \param line The line from which the log message is generated.
155*11be35a1SLionel Sambuc /// \param user_message The raw message to store.
156*11be35a1SLionel Sambuc void
log(const level message_level,const char * file,const int line,const std::string & user_message)157*11be35a1SLionel Sambuc logging::log(const level message_level, const char* file, const int line,
158*11be35a1SLionel Sambuc              const std::string& user_message)
159*11be35a1SLionel Sambuc {
160*11be35a1SLionel Sambuc     const datetime::timestamp now = datetime::timestamp::now();
161*11be35a1SLionel Sambuc     if (!first_timestamp)
162*11be35a1SLionel Sambuc         first_timestamp = now;
163*11be35a1SLionel Sambuc 
164*11be35a1SLionel Sambuc     if (auto_set_persistency) {
165*11be35a1SLionel Sambuc         // These values are hardcoded here for testing purposes.  The
166*11be35a1SLionel Sambuc         // application should call set_inmemory() by itself during
167*11be35a1SLionel Sambuc         // initialization to avoid this, so that it has explicit control on how
168*11be35a1SLionel Sambuc         // the call to set_persistency() happens.
169*11be35a1SLionel Sambuc         set_persistency("debug", fs::path("/dev/stderr"));
170*11be35a1SLionel Sambuc         auto_set_persistency = false;
171*11be35a1SLionel Sambuc     }
172*11be35a1SLionel Sambuc 
173*11be35a1SLionel Sambuc     if (message_level > log_level)
174*11be35a1SLionel Sambuc         return;
175*11be35a1SLionel Sambuc 
176*11be35a1SLionel Sambuc     // Update doc/troubleshooting.texi if you change the log format.
177*11be35a1SLionel Sambuc     const std::string message = F("%s %s %s %s:%s: %s") %
178*11be35a1SLionel Sambuc         now.strftime(timestamp_format) % level_to_char(message_level) %
179*11be35a1SLionel Sambuc         ::getpid() % file % line % user_message;
180*11be35a1SLionel Sambuc     if (logfile.get() == NULL)
181*11be35a1SLionel Sambuc         backlog.push_back(std::make_pair(message_level, message));
182*11be35a1SLionel Sambuc     else {
183*11be35a1SLionel Sambuc         INV(backlog.empty());
184*11be35a1SLionel Sambuc         (*logfile) << message << '\n';
185*11be35a1SLionel Sambuc         (*logfile).flush();
186*11be35a1SLionel Sambuc     }
187*11be35a1SLionel Sambuc }
188*11be35a1SLionel Sambuc 
189*11be35a1SLionel Sambuc 
190*11be35a1SLionel Sambuc /// Sets the logging to record messages in memory for later flushing.
191*11be35a1SLionel Sambuc void
set_inmemory(void)192*11be35a1SLionel Sambuc logging::set_inmemory(void)
193*11be35a1SLionel Sambuc {
194*11be35a1SLionel Sambuc     auto_set_persistency = false;
195*11be35a1SLionel Sambuc }
196*11be35a1SLionel Sambuc 
197*11be35a1SLionel Sambuc 
198*11be35a1SLionel Sambuc /// Makes the log persistent.
199*11be35a1SLionel Sambuc ///
200*11be35a1SLionel Sambuc /// Calling this function flushes the in-memory log, if any, to disk and sets
201*11be35a1SLionel Sambuc /// the logging module to send log entries to disk from this point onwards.
202*11be35a1SLionel Sambuc /// There is no way back, and the caller program should execute this function as
203*11be35a1SLionel Sambuc /// early as possible to ensure that a crash at startup does not discard too
204*11be35a1SLionel Sambuc /// many useful log entries.
205*11be35a1SLionel Sambuc ///
206*11be35a1SLionel Sambuc /// Any log entries above the provided new_level are discarded.
207*11be35a1SLionel Sambuc ///
208*11be35a1SLionel Sambuc /// \param new_level The new log level.
209*11be35a1SLionel Sambuc /// \param path The file to write the logs to.
210*11be35a1SLionel Sambuc ///
211*11be35a1SLionel Sambuc /// \throw std::range_error If the given log level is invalid.
212*11be35a1SLionel Sambuc /// \throw std::runtime_error If the given file cannot be created.
213*11be35a1SLionel Sambuc void
set_persistency(const std::string & new_level,const fs::path & path)214*11be35a1SLionel Sambuc logging::set_persistency(const std::string& new_level, const fs::path& path)
215*11be35a1SLionel Sambuc {
216*11be35a1SLionel Sambuc     auto_set_persistency = false;
217*11be35a1SLionel Sambuc 
218*11be35a1SLionel Sambuc     PRE(logfile.get() == NULL);
219*11be35a1SLionel Sambuc 
220*11be35a1SLionel Sambuc     // Update doc/troubleshooting.info if you change the log levels.
221*11be35a1SLionel Sambuc     if (new_level == "debug")
222*11be35a1SLionel Sambuc         log_level = level_debug;
223*11be35a1SLionel Sambuc     else if (new_level == "error")
224*11be35a1SLionel Sambuc         log_level = level_error;
225*11be35a1SLionel Sambuc     else if (new_level == "info")
226*11be35a1SLionel Sambuc         log_level = level_info;
227*11be35a1SLionel Sambuc     else if (new_level == "warning")
228*11be35a1SLionel Sambuc         log_level = level_warning;
229*11be35a1SLionel Sambuc     else
230*11be35a1SLionel Sambuc         throw std::range_error(F("Unrecognized log level '%s'") % new_level);
231*11be35a1SLionel Sambuc 
232*11be35a1SLionel Sambuc     logfile.reset(new std::ofstream(path.c_str()));
233*11be35a1SLionel Sambuc     if (!(*logfile))
234*11be35a1SLionel Sambuc         throw std::runtime_error(F("Failed to create log file %s") % path);
235*11be35a1SLionel Sambuc 
236*11be35a1SLionel Sambuc     for (std::vector< std::pair< logging::level, std::string > >::const_iterator
237*11be35a1SLionel Sambuc          iter = backlog.begin(); iter != backlog.end(); iter++) {
238*11be35a1SLionel Sambuc         if ((*iter).first <= log_level)
239*11be35a1SLionel Sambuc             (*logfile) << (*iter).second << '\n';
240*11be35a1SLionel Sambuc     }
241*11be35a1SLionel Sambuc     (*logfile).flush();
242*11be35a1SLionel Sambuc     backlog.clear();
243*11be35a1SLionel Sambuc }
244