logger_example.cc 12.2 KB
Newer Older
1
// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

/// \brief Example Program
///
17
18
19
20
21
/// Simple example program showing how to use the logger.  The various
/// command-line options let most aspects of the logger be exercised, so
/// making this a useful tool for testing.
///
/// See the usage() method for details of use.
22

23
#include <stdlib.h>
24
25
26
#include <unistd.h>
#include <string.h>

Stephen Morris's avatar
Stephen Morris committed
27
28
#include <boost/lexical_cast.hpp>

29
#include <iostream>
Stephen Morris's avatar
Stephen Morris committed
30
#include <string>
31
#include <vector>
32

33
34
#include <util/strutil.h>

35
#include <log/logger.h>
36
#include <log/logger_level.h>
Stephen Morris's avatar
Stephen Morris committed
37
#include <log/logger_manager.h>
38
#include <log/logger_name.h>
Stephen Morris's avatar
Stephen Morris committed
39
40
#include <log/logger_specification.h>
#include <log/macros.h>
41
42

// Include a set of message definitions.
43
#include <log/log_messages.h>
44
#include "util/interprocess_sync_null.h"
45
46

using namespace isc::log;
Stephen Morris's avatar
Stephen Morris committed
47
48
49
50
51
52
53
using namespace std;


// Print usage information

void usage() {
    cout <<
54
"logger_support_test [-h | [logger_spec] [[logger_spec]...]]\n"
Stephen Morris's avatar
Stephen Morris committed
55
"\n"
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"     -h            Print this message and exit\n"
"\n"
"The rest of the command line comprises the set of logger specifications.\n"
"Each specification is of the form:\n"
"\n"
"    -l logger  [-s severity] [-d dbglevel] output_spec] [[output_spec] ...\n"
"\n"
"where:\n"
"\n"
"    -l logger      Give the name of the logger to which the following\n"
"                   output specifications will apply.\n"
"\n"
"Each logger is followed by the indication of the serverity it is logging\n"
"and, if applicable, its debug level:\n"
Stephen Morris's avatar
Stephen Morris committed
70
"\n"
Stephen Morris's avatar
Stephen Morris committed
71
72
"   -d dbglevel     Debug level.  Only interpreted if the severity is 'debug'\n"
"                   this is a number between 0 and 99.\n"
Stephen Morris's avatar
Stephen Morris committed
73
74
75
"   -s severity     Set the severity of messages output.  'severity' is one\n"
"                   of 'debug', 'info', 'warn', 'error', 'fatal', the default\n"
"                   being 'info'.\n"
Stephen Morris's avatar
Stephen Morris committed
76
"\n"
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"The output specifications - there may be more than one per logger - detail\n"
"the output streams attached to the logger.  These are of the form:\n"
"\n"
"   -c stream | -f file [-m maxver] [-z maxsize] | -y facility\n"
"\n"
"These are:\n"
"\n"
"   -c stream       Send output to the console.  'stream' is one of 'stdout'\n"
"                   of 'stderr'.\n"
"   -f file         Send output to specified file, appending to existing file\n"
"                   if one exists.\n"
"   -y facility     Send output to the syslog file with the given facility\n"
"                   name (e.g. local1, cron etc.)\n"
"\n"
"The following can be specified for the file logger:\n"
"\n"
"   -m maxver       If file rolling is selected (by the maximum file size being\n"
"                   non-zero), the maximum number of versions to keep (defaults\n"
"                   to 0)\n"
"   -z maxsize      Maximum size of the file before the file is closed and a\n"
"                   new one opened.  The default of 0 means no maximum size.\n"
"\n"
"If none of -c, -f or -y is given, by default, output is sent to stdout.  If no\n"
"logger is specified, the default is the program's root logger ('example').\n";

Stephen Morris's avatar
Stephen Morris committed
102
}
103
104


105
106
// The program sets the attributes on the root logger and logs a set of
// messages.  Looking at the output determines whether the program worked.
107
108

int main(int argc, char** argv) {
109
    const char* ROOT_NAME = "example";
110

111
    bool                sw_found = false;   // Set true if switch found
Stephen Morris's avatar
Stephen Morris committed
112
113
    bool                c_found = false;    // Set true if "-c" found
    bool                f_found = false;    // Set true if "-f" found
114
    bool                y_found = false;    // Set true if "-y" found
Stephen Morris's avatar
Stephen Morris committed
115
    int                 option;             // For getopt() processing
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    OutputOption        def_opt;            // Default output option - used
                                            //    for initialization
    LoggerSpecification cur_spec(ROOT_NAME);// Current specification
    OutputOption        cur_opt;            // Current output option
    vector<LoggerSpecification> loggers;    // Set of logger specifications
    vector<OutputOption>        options;    // Output options for logger
    std::string                 severity;   // Severity set for logger

    // Initialize logging system - set the root logger name.
    LoggerManager manager;
    manager.init(ROOT_NAME);

    // In the parsing loop that follows, the construction of the logging
    // specification is always "one behind".  In other words, the parsing of
    // command-line options updates thge current logging specification/output
    // options.  When the flag indicating a new logger or output specification
    // is encountered, the previous one is added to the list.
    //
    // One complication is that there is deemed to be a default active when
    // the parsing starts (console output for the BIND 10 root logger).  This
    // is included in the logging specifications UNLESS the first switch on
    // the command line is a "-l" flag starting a new logger.  To track this,
    // the "sw_found" flag is set when a switch is completey processed. The
    // processing of "-l" will only add information for a previous logger to
    // the list if this flag is set.
    while ((option = getopt(argc, argv, "hc:d:f:l:m:s:y:z:")) != -1) {
142
        switch (option) {
143
144
145
146
147
148
149
        case 'c':   // Console output
            // New output spec.  If one was currently active, add it to the
            // list and reset the current output option to the defaults.
            if (c_found || f_found || y_found) {
                cur_spec.addOutputOption(cur_opt);
                cur_opt = def_opt;
                c_found = f_found = y_found = false;
Stephen Morris's avatar
Stephen Morris committed
150
151
            }

152
            // Set the output option for this switch.
Stephen Morris's avatar
Stephen Morris committed
153
            c_found = true;
154
            cur_opt.destination = OutputOption::DEST_CONSOLE;
Stephen Morris's avatar
Stephen Morris committed
155
            if (strcmp(optarg, "stdout") == 0) {
156
                cur_opt.stream = OutputOption::STR_STDOUT;
Stephen Morris's avatar
Stephen Morris committed
157
158

            } else if (strcmp(optarg, "stderr") == 0) {
159
                cur_opt.stream = OutputOption::STR_STDERR;
Stephen Morris's avatar
Stephen Morris committed
160
161
162
163
164
165
166

            } else {
                cerr << "Unrecognised console option: " << optarg << "\n";
                return (1);
            }
            break;

167
168
        case 'd':   // Debug level
            cur_spec.setDbglevel(boost::lexical_cast<int>(optarg));
Stephen Morris's avatar
Stephen Morris committed
169
170
            break;

171
172
173
174
175
176
177
        case 'f':   // File output specification
            // New output spec.  If one was currently active, add it to the
            // list and reset the current output option to the defaults.
            if (c_found || f_found || y_found) {
                cur_spec.addOutputOption(cur_opt);
                cur_opt = def_opt;
                c_found = f_found = y_found = false;
Stephen Morris's avatar
Stephen Morris committed
178
179
            }

180
            // Set the output option for this switch.
Stephen Morris's avatar
Stephen Morris committed
181
            f_found = true;
182
183
            cur_opt.destination = OutputOption::DEST_FILE;
            cur_opt.filename = optarg;
Stephen Morris's avatar
Stephen Morris committed
184
185
            break;

186
        case 'h':   // Help
Stephen Morris's avatar
Stephen Morris committed
187
188
189
            usage();
            return (0);

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        case 'l':   // Logger
            // If a current specification is active, add the last output option
            // to it, add it to the list and reset.  A specification is active
            // if at least one switch has been previously found.
            if (sw_found) {
                cur_spec.addOutputOption(cur_opt);
                loggers.push_back(cur_spec);
                cur_spec.reset();
            }

            // Set the logger name
            cur_spec.setName(std::string(optarg));

            // Reset the output option to the default.
            cur_opt = def_opt;

            // Indicate nothing is found to prevent the console option (the
            // default output option) being added to the output list if an
            // output option is found.
            c_found = f_found = y_found = false;
            break;

        case 'm':   // Maximum file version
            if (!f_found) {
                std::cerr << "Attempt to set maximum version (-m) "
                             "outside of file output specification\n";
                return (1);
            }
            try {
                cur_opt.maxsize = boost::lexical_cast<unsigned int>(optarg);
            } catch (boost::bad_lexical_cast&) {
                std::cerr << "Maximum version (-m) argument must be a positive "
                             "integer\n";
                return (1);
            }
            break;

        case 's':   // Severity
            severity = optarg;
            isc::util::str::uppercase(severity);
            cur_spec.setSeverity(getSeverity(severity));
            break;

        case 'y':   // Syslog output
            // New output spec.  If one was currently active, add it to the
            // list and reset the current output option to the defaults.
            if (c_found || f_found || y_found) {
                cur_spec.addOutputOption(cur_opt);
                cur_opt = def_opt;
                c_found = f_found = y_found = false;
            }
            y_found = true;
            cur_opt.destination = OutputOption::DEST_SYSLOG;
            cur_opt.facility = optarg;
            break;

        case 'z':   // Maximum size
            if (! f_found) {
                std::cerr << "Attempt to set file size (-z) "
                             "outside of file output specification\n";
                return (1);
            }
            try {
                cur_opt.maxsize = boost::lexical_cast<size_t>(optarg);
            } catch (boost::bad_lexical_cast&) {
                std::cerr << "File size (-z) argument must be a positive "
                             "integer\n";
                return (1);
Stephen Morris's avatar
Stephen Morris committed
258
259
260
            }
            break;

261

Stephen Morris's avatar
Stephen Morris committed
262
263
264
265
        default:
            std::cerr << "Unrecognised option: " <<
                static_cast<char>(option) << "\n";
            return (1);
266
        }
267
268
269

        // Have found at least one command-line switch, so note the fact.
        sw_found = true;
270
271
    }

272
273
274
    // Add the current (unfinished specification) to the list.
    cur_spec.addOutputOption(cur_opt);
    loggers.push_back(cur_spec);
Stephen Morris's avatar
Stephen Morris committed
275

276
277
    // Set the logging options.
    manager.process(loggers.begin(), loggers.end());
Stephen Morris's avatar
Stephen Morris committed
278

Stephen Morris's avatar
Stephen Morris committed
279
280
281
282
283
    // Set the local file
    if (optind < argc) {
        LoggerManager::readLocalMessageFile(argv[optind]);
    }

284
285
    // Log a few messages to different loggers.
    isc::log::Logger logger_ex(ROOT_NAME);
286
    logger_ex.setInterprocessSync(new isc::util::InterprocessSyncNull("logger"));
287
    isc::log::Logger logger_alpha("alpha");
288
    logger_alpha.setInterprocessSync(new isc::util::InterprocessSyncNull("logger"));
289
    isc::log::Logger logger_beta("beta");
290
    logger_beta.setInterprocessSync(new isc::util::InterprocessSyncNull("logger"));
291

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    LOG_FATAL(logger_ex, LOG_WRITE_ERROR).arg("test1").arg("42");
    LOG_ERROR(logger_ex, LOG_READING_LOCAL_FILE).arg("dummy/file");
    LOG_WARN(logger_ex, LOG_BAD_STREAM).arg("example");
    LOG_WARN(logger_alpha, LOG_READ_ERROR).arg("a.txt").arg("dummy reason");
    LOG_INFO(logger_alpha, LOG_INPUT_OPEN_FAIL).arg("example.msg").arg("dummy reason");
    LOG_DEBUG(logger_ex, 0, LOG_READING_LOCAL_FILE).arg("example/0");
    LOG_DEBUG(logger_ex, 24, LOG_READING_LOCAL_FILE).arg("example/24");
    LOG_DEBUG(logger_ex, 25, LOG_READING_LOCAL_FILE).arg("example/25");
    LOG_DEBUG(logger_ex, 26, LOG_READING_LOCAL_FILE).arg("example/26");
    LOG_FATAL(logger_beta, LOG_BAD_SEVERITY).arg("beta_fatal");
    LOG_ERROR(logger_beta, LOG_BAD_DESTINATION).arg("beta_error");
    LOG_WARN(logger_beta, LOG_BAD_STREAM).arg("beta_warn");
    LOG_INFO(logger_beta, LOG_READ_ERROR).arg("beta").arg("info");
    LOG_DEBUG(logger_beta, 25, LOG_BAD_SEVERITY).arg("beta/25");
    LOG_DEBUG(logger_beta, 26, LOG_BAD_SEVERITY).arg("beta/26");
307

308
    return (0);
309
}