1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3 * Copyright (c) 2017, Intel Corporation
4 * All rights reserved.
5 */
6 #include <stdlib.h>
7 #include <syslog.h>
8 #include "util.h"
9 #include "logging.h"
10
11 /**
12 * This function that implements the GLogFunc prototype. It is intended
13 * for use as a log handler function for glib logging.
14 */
15 void
syslog_log_handler(const char * log_domain,GLogLevelFlags log_level,const char * message,gpointer log_config_list)16 syslog_log_handler (const char *log_domain,
17 GLogLevelFlags log_level,
18 const char *message,
19 gpointer log_config_list)
20 {
21 UNUSED_PARAM(log_domain);
22 UNUSED_PARAM(log_config_list);
23
24 switch (log_level) {
25 case G_LOG_FLAG_FATAL:
26 syslog (LOG_ALERT, "%s", message);
27 break;
28 case G_LOG_LEVEL_ERROR:
29 syslog (LOG_ERR, "%s", message);
30 break;
31 case G_LOG_LEVEL_CRITICAL:
32 syslog (LOG_CRIT, "%s", message);
33 break;
34 case G_LOG_LEVEL_WARNING:
35 syslog (LOG_WARNING, "%s", message);
36 break;
37 case G_LOG_LEVEL_MESSAGE:
38 syslog (LOG_NOTICE, "%s", message);
39 break;
40 case G_LOG_LEVEL_INFO:
41 syslog (LOG_INFO, "%s", message);
42 break;
43 case G_LOG_LEVEL_DEBUG:
44 syslog (LOG_DEBUG, "%s", message);
45 break;
46 default:
47 syslog (LOG_INFO, "%s", message);
48 }
49 }
50 /*
51 * The G_MESSAGES_DEBUG environment variable is a space separated list of
52 * glib logging domains that we want to see debug and info messages from.
53 * The right way to do this is to declare a logging domain for the application
54 * but for now we simply look for the special value of "all" and enable info
55 * and debug messages if it's set.
56 */
57 int
get_enabled_log_levels(void)58 get_enabled_log_levels (void)
59 {
60 gchar *g_log_domains = NULL;
61
62 g_log_domains = getenv ("G_MESSAGES_DEBUG");
63 if (g_log_domains == NULL) {
64 return LOG_LEVEL_DEFAULT;
65 }
66 if (g_strcmp0 (g_log_domains, "all") == 0) {
67 return LOG_LEVEL_ALL;
68 } else {
69 return LOG_LEVEL_DEFAULT;
70 }
71 }
72 /**
73 * Convenience function to set logger for GLog.
74 */
75 gint
set_logger(gchar * name)76 set_logger (gchar *name)
77 {
78 int enabled_log_levels = 0;
79
80 if (g_strcmp0 (name, "syslog") == 0) {
81 enabled_log_levels = get_enabled_log_levels ();
82 g_log_set_handler (NULL,
83 enabled_log_levels | G_LOG_FLAG_FATAL | \
84 G_LOG_FLAG_RECURSION,
85 syslog_log_handler,
86 NULL);
87 return 0;
88 } else if (g_strcmp0 (name, "stdout") == 0) {
89 /* stdout is the default for g_log, nothing to do but return 0 */
90 g_info ("logging to stdout");
91 return 0;
92 }
93 return -1;
94 }
95