Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / tools / crash_service / caps / logger_win.cc
blob13b53612fec6f53d4ab2cd210cc130fed82db343
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.
5 #include <windows.h>
6 #include <time.h>
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"
13 namespace {
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) {
26 if (txt.empty())
27 return true;
28 DWORD written;
29 auto rc = ::WriteFile(file, txt.c_str(),
30 static_cast<DWORD>(txt.size()),
31 &written,
32 nullptr);
33 return (rc == TRUE);
36 // Uses |kMessages| at |index| above to write to disk a formatted log line.
37 bool WriteFormattedLogLine(HANDLE file, size_t index, ...) {
38 va_list ap;
39 va_start(ap, 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());
44 va_end(ap);
45 return rc;
48 // Returns the current time and date formatted in standard C style.
49 std::string DateTime() {
50 time_t current_time = 0;
51 time(&current_time);
52 struct tm local_time = {0};
53 char time_buf[26] = {0};
54 localtime_s(&local_time, &current_time);
55 asctime_s(time_buf, &local_time);
56 time_buf[24] = '\0';
57 return time_buf;
60 } // namespace
62 namespace caps {
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
67 // for anything else.
68 DWORD kShareAll = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
69 file_ = ::CreateFile(logfile.value().c_str(),
70 FILE_APPEND_DATA, kShareAll,
71 nullptr,
72 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,
73 nullptr);
74 if (file_ == INVALID_HANDLE_VALUE)
75 return;
76 WriteFormattedLogLine(
77 file_, 0, ::GetCurrentProcessId(), PRODUCT_VERSION, DateTime().c_str());
80 Logger::~Logger() {
81 if (file_ != INVALID_HANDLE_VALUE) {
82 WriteFormattedLogLine(
83 file_, 1, ::GetCurrentProcessId(), DateTime().c_str());
84 ::CloseHandle(file_);
88 } // namespace caps