OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012 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 #ifndef THIRD_PARTY_LEVELDATABASE_CHROMIUM_LOGGER_H_ |
| 6 #define THIRD_PARTY_LEVELDATABASE_CHROMIUM_LOGGER_H_ |
| 7 |
| 8 #include <algorithm> |
| 9 #include <stdio.h> |
| 10 #include "base/string_util.h" |
| 11 #include "base/time.h" |
| 12 #include "leveldb/env.h" |
| 13 |
| 14 namespace leveldb { |
| 15 |
| 16 class ChromiumLogger : public Logger { |
| 17 public: |
| 18 ChromiumLogger(FILE* f) : file_(f) { } |
| 19 virtual ~ChromiumLogger() { |
| 20 fclose(file_); |
| 21 } |
| 22 virtual void Logv(const char* format, va_list ap) { |
| 23 const long long unsigned int thread_id = |
| 24 ::base::PlatformThread::CurrentId(); |
| 25 |
| 26 // We try twice: the first time with a fixed-size stack allocated buffer, |
| 27 // and the second time with a much larger dynamically allocated buffer. |
| 28 char buffer[500]; |
| 29 for (int iter = 0; iter < 2; iter++) { |
| 30 char* base; |
| 31 int bufsize; |
| 32 if (iter == 0) { |
| 33 bufsize = sizeof(buffer); |
| 34 base = buffer; |
| 35 } else { |
| 36 bufsize = 30000; |
| 37 base = new char[bufsize]; |
| 38 } |
| 39 char* p = base; |
| 40 char* limit = base + bufsize; |
| 41 |
| 42 ::base::Time::Exploded t; |
| 43 ::base::Time::Now().LocalExplode(&t); |
| 44 |
| 45 p += ::base::snprintf(p, limit - p, |
| 46 "%04d/%02d/%02d-%02d:%02d:%02d.%03d %lld ", |
| 47 t.year, |
| 48 t.month, |
| 49 t.day_of_month, |
| 50 t.hour, |
| 51 t.minute, |
| 52 t.second, |
| 53 t.millisecond, |
| 54 thread_id); |
| 55 |
| 56 // Print the message |
| 57 if (p < limit) { |
| 58 va_list backup_ap; |
| 59 GG_VA_COPY(backup_ap, ap); |
| 60 p += vsnprintf(p, limit - p, format, backup_ap); |
| 61 va_end(backup_ap); |
| 62 } |
| 63 |
| 64 // Truncate to available space if necessary |
| 65 if (p >= limit) { |
| 66 if (iter == 0) { |
| 67 continue; // Try again with larger buffer |
| 68 } else { |
| 69 p = limit - 1; |
| 70 } |
| 71 } |
| 72 |
| 73 // Add newline if necessary |
| 74 if (p == base || p[-1] != '\n') { |
| 75 *p++ = '\n'; |
| 76 } |
| 77 |
| 78 assert(p <= limit); |
| 79 fwrite(base, 1, p - base, file_); |
| 80 fflush(file_); |
| 81 if (base != buffer) { |
| 82 delete[] base; |
| 83 } |
| 84 break; |
| 85 } |
| 86 } |
| 87 private: |
| 88 FILE* file_; |
| 89 }; |
| 90 |
| 91 } // namespace leveldb |
| 92 |
| 93 #endif // THIRD_PARTY_LEVELDATABASE_CHROMIUM_LOGGER_H_ |
OLD | NEW |