1 // Copyright 2015 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.
8 #include "base/files/file_path.h"
9 #include "base/strings/stringprintf.h"
10 #include "chrome/tools/crash_service/caps/logger_win.h"
11 #include "components/version_info/version_info_values.h"
14 // Every message has this structure:
15 // <index>~ <tick_count> <message> ~\n"
16 const char kMessageHeader
[] = "%03d~ %08x %s ~\n";
18 // Do not re-order these messages. Only add at the end.
19 const char* kMessages
[] {
20 "start pid(%lu) version(%s) time(%s)", // 0
21 "exit pid(%lu) time(%s)", // 1
22 "instance found", // 2
25 bool WriteLogLine(HANDLE file
, const std::string
& txt
) {
29 auto rc
= ::WriteFile(file
, txt
.c_str(),
30 static_cast<DWORD
>(txt
.size()),
36 // Uses |kMessages| at |index| above to write to disk a formatted log line.
37 bool WriteFormattedLogLine(HANDLE file
, size_t index
, ...) {
40 auto fmt
= base::StringPrintf(
41 kMessageHeader
, index
, ::GetTickCount(), kMessages
[index
]);
42 auto msg
= base::StringPrintV(fmt
.c_str(), ap
);
43 auto rc
= WriteLogLine(file
, msg
.c_str());
48 // Returns the current time and date formatted in standard C style.
49 std::string
DateTime() {
50 time_t current_time
= 0;
52 struct tm local_time
= {0};
53 char time_buf
[26] = {0};
54 localtime_s(&local_time
, ¤t_time
);
55 asctime_s(time_buf
, &local_time
);
64 Logger::Logger(const base::FilePath
& path
) : file_(INVALID_HANDLE_VALUE
) {
65 auto logfile
= path
.Append(L
"caps_log.txt");
66 // Opening a file like so allows atomic appends, but can't be used
68 DWORD kShareAll
= FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
69 file_
= ::CreateFile(logfile
.value().c_str(),
70 FILE_APPEND_DATA
, kShareAll
,
72 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
,
74 if (file_
== INVALID_HANDLE_VALUE
)
76 WriteFormattedLogLine(
77 file_
, 0, ::GetCurrentProcessId(), PRODUCT_VERSION
, DateTime().c_str());
81 if (file_
!= INVALID_HANDLE_VALUE
) {
82 WriteFormattedLogLine(
83 file_
, 1, ::GetCurrentProcessId(), DateTime().c_str());