1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/syslog_logging.h"
10 #include "base/callback_helpers.h"
11 #include "base/debug/stack_trace.h"
12 #elif defined(OS_LINUX)
13 // <syslog.h> defines LOG_INFO, LOG_WARNING macros that could conflict with
14 // base::LOG_INFO, base::LOG_WARNING.
29 std::string* g_event_source_name = nullptr;
30 uint16_t g_category = 0;
31 uint32_t g_event_id = 0;
35 void SetEventSource(const std::string& name,
38 DCHECK_EQ(nullptr, g_event_source_name);
39 g_event_source_name = new std::string(name);
40 g_category = category;
41 g_event_id = event_id;
44 void ResetEventSourceForTesting() {
45 delete g_event_source_name;
46 g_event_source_name = nullptr;
49 #endif // defined(OS_WIN)
51 EventLogMessage::EventLogMessage(const char* file,
54 : log_message_(file, line, severity) {
57 EventLogMessage::~EventLogMessage() {
59 // If g_event_source_name is nullptr (which it is per default) SYSLOG will
60 // degrade gracefully to regular LOG. If you see this happening most probably
61 // you are using SYSLOG before you called SetEventSourceName.
62 if (g_event_source_name == nullptr)
65 HANDLE event_log_handle =
66 RegisterEventSourceA(nullptr, g_event_source_name->c_str());
67 if (event_log_handle == nullptr) {
68 stream() << " !!NOT ADDED TO EVENTLOG!!";
72 base::ScopedClosureRunner auto_deregister(
73 base::Bind(base::IgnoreResult(&DeregisterEventSource), event_log_handle));
74 std::string message(log_message_.str());
75 WORD log_type = EVENTLOG_ERROR_TYPE;
76 switch (log_message_.severity()) {
78 log_type = EVENTLOG_INFORMATION_TYPE;
81 log_type = EVENTLOG_WARNING_TYPE;
85 // The price of getting the stack trace is not worth the hassle for
86 // non-error conditions.
87 base::debug::StackTrace trace;
88 message.append(trace.ToString());
89 log_type = EVENTLOG_ERROR_TYPE;
92 LPCSTR strings[1] = {message.data()};
93 if (!ReportEventA(event_log_handle, log_type, g_category, g_event_id, nullptr,
94 1, 0, strings, nullptr)) {
95 stream() << " !!NOT ADDED TO EVENTLOG!!";
97 #elif defined(OS_LINUX)
98 const char kEventSource[] = "chrome";
99 openlog(kEventSource, LOG_NOWAIT | LOG_PID, LOG_USER);
100 // We can't use the defined names for the logging severity from syslog.h
101 // because they collide with the names of our own severity levels. Therefore
102 // we use the actual values which of course do not match ours.
103 // See sys/syslog.h for reference.
105 switch (log_message_.severity()) {
119 syslog(priority, "%s", log_message_.str().c_str());
121 #endif // defined(OS_WIN)
124 } // namespace logging