]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/dolog.hh
Add a disable-syslog setting
[thirdparty/pdns.git] / pdns / dolog.hh
CommitLineData
64e4ebb4 1#pragma once
2#include <iostream>
3#include <sstream>
4#include <syslog.h>
5
6/* This file is intended not to be metronome specific, and is simple example of C++2011
7 variadic templates in action.
8
9 The goal is rapid easy to use logging to console & syslog.
10
11 Usage:
12 string address="localhost";
fb7f8ec3 13 vinfolog("Got TCP connection from %s", remote);
64e4ebb4 14 infolog("Bound to %s port %d", address, port);
15 warnlog("Query took %d milliseconds", 1232.4); // yes, %d
16 errlog("Unable to bind to %s: %s", ca.toStringWithPort(), strerr(errno));
17
18 If bool g_console is true, will log to stdout. Will syslog in any case with LOG_INFO,
fb7f8ec3 19 LOG_WARNING, LOG_ERR respectively. If g_verbose=false, vinfolog is a noop.
64e4ebb4 20 More generically, dolog(someiostream, "Hello %s", stream) will log to someiostream
21
22 This will happily print a string to %d! Doesn't do further format processing.
23*/
24
25inline void dolog(std::ostream& os, const char*s)
26{
27 os<<s;
28}
29
30template<typename T, typename... Args>
31void dolog(std::ostream& os, const char* s, T value, Args... args)
32{
33 while (*s) {
34 if (*s == '%') {
35 if (*(s + 1) == '%') {
36 ++s;
37 }
38 else {
39 os << value;
40 s += 2;
41 dolog(os, s, args...);
42 return;
43 }
44 }
45 os << *s++;
46 }
47}
48
49extern bool g_console;
50extern bool g_verbose;
51
52template<typename... Args>
53void genlog(int level, const char* s, Args... args)
54{
55 std::ostringstream str;
56 dolog(str, s, args...);
57 syslog(level, "%s", str.str().c_str());
58 if(g_console)
59 std::cout<<str.str()<<std::endl;
60}
61
b2ad6825 62
63#define vinfolog if(g_verbose)infolog
64
64e4ebb4 65template<typename... Args>
66void infolog(const char* s, Args... args)
67{
fb7f8ec3 68 genlog(LOG_INFO, s, args...);
64e4ebb4 69}
70
71template<typename... Args>
72void warnlog(const char* s, Args... args)
73{
74 genlog(LOG_WARNING, s, args...);
75}
76
77template<typename... Args>
78void errlog(const char* s, Args... args)
79{
80 genlog(LOG_ERR, s, args...);
81}
b2ad6825 82