• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2009 Google Inc. All Rights Reserved.
2 
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "logger.h"
16 
17 #include <pthread.h>
18 #include <stdarg.h>
19 #include <stdio.h>
20 #include <time.h>
21 #include <unistd.h>
22 
23 #include <string>
24 #include <vector>
25 
26 // This file must work with autoconf on its public version,
27 // so these includes are correct.
28 #include "sattypes.h"
29 
30 
GlobalLogger()31 Logger *Logger::GlobalLogger() {
32   static Logger logger;
33   return &logger;
34 }
35 
VLogF(int priority,const char * format,va_list args)36 void Logger::VLogF(int priority, const char *format, va_list args) {
37   if (priority > verbosity_) {
38     return;
39   }
40   char buffer[4096];
41   size_t length = 0;
42   if (log_timestamps_) {
43     time_t raw_time;
44     time(&raw_time);
45     struct tm time_struct;
46     localtime_r(&raw_time, &time_struct);
47     length = strftime(buffer, sizeof(buffer), "%Y/%m/%d-%H:%M:%S(%Z) ",
48                       &time_struct);
49     LOGGER_ASSERT(length);  // Catch if the buffer is set too small.
50   }
51   length += vsnprintf(buffer + length, sizeof(buffer) - length, format, args);
52   if (length >= sizeof(buffer)) {
53     length = sizeof(buffer);
54     buffer[sizeof(buffer) - 1] = '\n';
55   }
56   QueueLogLine(new string(buffer, length));
57 }
58 
StartThread()59 void Logger::StartThread() {
60   LOGGER_ASSERT(!thread_running_);
61   thread_running_ = true;
62   LOGGER_ASSERT(0 == pthread_create(&thread_, NULL, &StartRoutine, this));
63 }
64 
StopThread()65 void Logger::StopThread() {
66   // Allow this to be called before the thread has started.
67   if (!thread_running_) {
68     return;
69   }
70   thread_running_ = false;
71   int retval = pthread_mutex_lock(&queued_lines_mutex_);
72   LOGGER_ASSERT(0 == retval);
73   bool need_cond_signal = queued_lines_.empty();
74   queued_lines_.push_back(NULL);
75   retval = pthread_mutex_unlock(&queued_lines_mutex_);
76   LOGGER_ASSERT(0 == retval);
77   if (need_cond_signal) {
78     retval = pthread_cond_signal(&queued_lines_cond_);
79     LOGGER_ASSERT(0 == retval);
80   }
81   retval = pthread_join(thread_, NULL);
82   LOGGER_ASSERT(0 == retval);
83 }
84 
Logger()85 Logger::Logger()
86     : verbosity_(20),
87       log_fd_(-1),
88       thread_running_(false),
89       log_timestamps_(true) {
90   LOGGER_ASSERT(0 == pthread_mutex_init(&queued_lines_mutex_, NULL));
91   LOGGER_ASSERT(0 == pthread_cond_init(&queued_lines_cond_, NULL));
92   LOGGER_ASSERT(0 == pthread_cond_init(&full_queue_cond_, NULL));
93 }
94 
~Logger()95 Logger::~Logger() {
96   LOGGER_ASSERT(0 == pthread_mutex_destroy(&queued_lines_mutex_));
97   LOGGER_ASSERT(0 == pthread_cond_destroy(&queued_lines_cond_));
98   LOGGER_ASSERT(0 == pthread_cond_destroy(&full_queue_cond_));
99 }
100 
QueueLogLine(string * line)101 void Logger::QueueLogLine(string *line) {
102   LOGGER_ASSERT(line != NULL);
103   LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
104   if (thread_running_) {
105     if (queued_lines_.size() >= kMaxQueueSize) {
106       LOGGER_ASSERT(0 == pthread_cond_wait(&full_queue_cond_,
107                                            &queued_lines_mutex_));
108     }
109     if (queued_lines_.empty()) {
110       LOGGER_ASSERT(0 == pthread_cond_signal(&queued_lines_cond_));
111     }
112     queued_lines_.push_back(line);
113   } else {
114     WriteAndDeleteLogLine(line);
115   }
116   LOGGER_ASSERT(0 == pthread_mutex_unlock(&queued_lines_mutex_));
117 }
118 
WriteAndDeleteLogLine(string * line)119 void Logger::WriteAndDeleteLogLine(string *line) {
120   LOGGER_ASSERT(line != NULL);
121   ssize_t bytes_written;
122   if (log_fd_ >= 0) {
123     bytes_written = write(log_fd_, line->data(), line->size());
124     LOGGER_ASSERT(bytes_written == static_cast<ssize_t>(line->size()));
125   }
126   bytes_written = write(STDOUT_FILENO, line->data(), line->size());
127   LOGGER_ASSERT(bytes_written == static_cast<ssize_t>(line->size()));
128   delete line;
129 }
130 
StartRoutine(void * ptr)131 void *Logger::StartRoutine(void *ptr) {
132   Logger *self = static_cast<Logger*>(ptr);
133   self->ThreadMain();
134   return NULL;
135 }
136 
ThreadMain()137 void Logger::ThreadMain() {
138   vector<string*> local_queue;
139   LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
140 
141   for (;;) {
142     if (queued_lines_.empty()) {
143       LOGGER_ASSERT(0 == pthread_cond_wait(&queued_lines_cond_,
144                                            &queued_lines_mutex_));
145       continue;
146     }
147 
148     // We move the log lines into a local queue so we can release the lock
149     // while writing them to disk, preventing other threads from blocking on
150     // our writes.
151     local_queue.swap(queued_lines_);
152     if (local_queue.size() >= kMaxQueueSize) {
153       LOGGER_ASSERT(0 == pthread_cond_broadcast(&full_queue_cond_));
154     }
155 
156     // Unlock while we process our local queue.
157     LOGGER_ASSERT(0 == pthread_mutex_unlock(&queued_lines_mutex_));
158     for (vector<string*>::const_iterator it = local_queue.begin();
159          it != local_queue.end(); ++it) {
160       if (*it == NULL) {
161         // NULL is guaranteed to be at the end.
162         return;
163       }
164       WriteAndDeleteLogLine(*it);
165     }
166     local_queue.clear();
167     // We must hold the lock at the start of each iteration of this for loop.
168     LOGGER_ASSERT(0 == pthread_mutex_lock(&queued_lines_mutex_));
169   }
170 }
171