blob: 1d3daf9e83034f523bb48afe1058a7ba813e63ac [file] [log] [blame]
pastarmovj114af1b2016-09-20 23:58:13 +09001// 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.
4
5#include "base/debug/stack_trace.h"
6#include "base/syslog_logging.h"
7
8#if defined(OS_WIN)
9#include <windows.h>
10#elif defined(OS_LINUX)
11#include <syslog.h>
12#endif
13
14#include <cstring>
15#include <ostream>
16#include <string>
17
18namespace logging {
19
20EventLogMessage::EventLogMessage(const char* file,
21 int line,
22 LogSeverity severity)
23 : log_message_(file, line, severity) {
24}
25
26EventLogMessage::~EventLogMessage() {
27#if defined(OS_WIN)
28 const char kEventSource[] = "chrome";
29 HANDLE event_log_handle = RegisterEventSourceA(NULL, kEventSource);
30 if (event_log_handle == NULL) {
31 stream() << " !!NOT ADDED TO EVENTLOG!!";
32 return;
33 }
34
35 std::string message(log_message_.str());
36 LPCSTR strings[1] = {message.data()};
37 WORD log_type = EVENTLOG_ERROR_TYPE;
38 switch (log_message_.severity()) {
39 case LOG_INFO:
40 log_type = EVENTLOG_INFORMATION_TYPE;
41 break;
42 case LOG_WARNING:
43 log_type = EVENTLOG_WARNING_TYPE;
44 break;
45 case LOG_ERROR:
46 case LOG_FATAL:
47 // The price of getting the stack trace is not worth the hassle for
48 // non-error conditions.
49 base::debug::StackTrace trace;
50 message.append(trace.ToString());
51 log_type = EVENTLOG_ERROR_TYPE;
52 break;
53 }
54 // TODO(pastarmovj): Register Chrome's event log resource types to make the
55 // entries nicer. 1337 is just a made up event id type.
56 if (!ReportEventA(event_log_handle, log_type, 0, 1337, NULL, 1, 0,
57 strings, NULL)) {
58 stream() << " !!NOT ADDED TO EVENTLOG!!";
59 }
60 DeregisterEventSource(event_log_handle);
61#elif defined(OS_LINUX)
62 const char kEventSource[] = "chrome";
63 openlog(kEventSource, LOG_NOWAIT | LOG_PID, LOG_USER);
64 // We can't use the defined names for the logging severity from syslog.h
65 // because they collide with the names of our own severity levels. Therefore
66 // we use the actual values which of course do not match ours.
67 // See sys/syslog.h for reference.
68 int priority = 3;
69 switch (log_message_.severity()) {
70 case LOG_INFO:
71 priority = 6;
72 break;
73 case LOG_WARNING:
74 priority = 4;
75 break;
76 case LOG_ERROR:
77 priority = 3;
78 break;
79 case LOG_FATAL:
80 priority = 2;
81 break;
82 }
83 syslog(priority, "%s", log_message_.str().c_str());
84 closelog();
85#endif // defined(OS_WIN)
86}
87
88} // namespace logging