1 /* 2 * Copyright (c) 2016-present, Facebook, Inc. 3 * All rights reserved. 4 * 5 * This source code is licensed under both the BSD-style license (found in the 6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 * in the COPYING file in the root directory of this source tree). 8 */ 9 #pragma once 10 11 #include <cstdio> 12 #include <mutex> 13 14 namespace pzstd { 15 16 constexpr int kLogError = 1; 17 constexpr int kLogInfo = 2; 18 constexpr int kLogDebug = 3; 19 constexpr int kLogVerbose = 4; 20 21 class Logger { 22 std::mutex mutex_; 23 FILE* out_; 24 const int level_; 25 26 using Clock = std::chrono::system_clock; 27 Clock::time_point lastUpdate_; 28 std::chrono::milliseconds refreshRate_; 29 30 public: 31 explicit Logger(int level, FILE* out = stderr) out_(out)32 : out_(out), level_(level), lastUpdate_(Clock::now()), 33 refreshRate_(150) {} 34 35 logsAt(int level)36 bool logsAt(int level) { 37 return level <= level_; 38 } 39 40 template <typename... Args> operator()41 void operator()(int level, const char *fmt, Args... args) { 42 if (level > level_) { 43 return; 44 } 45 std::lock_guard<std::mutex> lock(mutex_); 46 std::fprintf(out_, fmt, args...); 47 } 48 49 template <typename... Args> update(int level,const char * fmt,Args...args)50 void update(int level, const char *fmt, Args... args) { 51 if (level > level_) { 52 return; 53 } 54 std::lock_guard<std::mutex> lock(mutex_); 55 auto now = Clock::now(); 56 if (now - lastUpdate_ > refreshRate_) { 57 lastUpdate_ = now; 58 std::fprintf(out_, "\r"); 59 std::fprintf(out_, fmt, args...); 60 } 61 } 62 clear(int level)63 void clear(int level) { 64 if (level > level_) { 65 return; 66 } 67 std::lock_guard<std::mutex> lock(mutex_); 68 std::fprintf(out_, "\r%79s\r", ""); 69 } 70 }; 71 72 } 73