Anders Carlsson | 3b3364e | 2018-01-30 15:46:13 +0100 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2018 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | #import "WebRTC/RTCCallbackLogger.h" |
| 12 | |
| 13 | #include <memory> |
| 14 | |
| 15 | #include "rtc_base/checks.h" |
| 16 | #include "rtc_base/logging.h" |
| 17 | #include "rtc_base/logsinks.h" |
| 18 | |
| 19 | class CallbackLogSink : public rtc::LogSink { |
| 20 | public: |
| 21 | CallbackLogSink(void (^callbackHandler)(NSString *message)) { |
| 22 | callback_handler_ = callbackHandler; |
| 23 | } |
| 24 | |
| 25 | ~CallbackLogSink() override { callback_handler_ = nil; } |
| 26 | |
| 27 | void OnLogMessage(const std::string &message) override { |
| 28 | if (callback_handler_) { |
| 29 | callback_handler_([NSString stringWithUTF8String:message.c_str()]); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | private: |
| 34 | void (^callback_handler_)(NSString *message); |
| 35 | }; |
| 36 | |
| 37 | @implementation RTCCallbackLogger { |
| 38 | BOOL _hasStarted; |
| 39 | std::unique_ptr<CallbackLogSink> _logSink; |
| 40 | } |
| 41 | |
| 42 | @synthesize severity = _severity; |
| 43 | |
| 44 | - (void)dealloc { |
| 45 | [self stop]; |
| 46 | } |
| 47 | |
| 48 | - (void)start:(nullable void (^)(NSString *))callback { |
| 49 | if (_hasStarted) { |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | _logSink.reset(new CallbackLogSink(callback)); |
| 54 | |
| 55 | rtc::LogMessage::AddLogToStream(_logSink.get(), [self rtcSeverity]); |
| 56 | _hasStarted = YES; |
| 57 | } |
| 58 | |
| 59 | - (void)stop { |
| 60 | if (!_hasStarted) { |
| 61 | return; |
| 62 | } |
| 63 | RTC_DCHECK(_logSink); |
| 64 | rtc::LogMessage::RemoveLogToStream(_logSink.get()); |
| 65 | _hasStarted = NO; |
| 66 | _logSink.reset(); |
| 67 | } |
| 68 | |
| 69 | #pragma mark - Private |
| 70 | |
| 71 | - (rtc::LoggingSeverity)rtcSeverity { |
| 72 | switch (_severity) { |
| 73 | case RTCLoggingSeverityVerbose: |
| 74 | return rtc::LS_VERBOSE; |
| 75 | case RTCLoggingSeverityInfo: |
| 76 | return rtc::LS_INFO; |
| 77 | case RTCLoggingSeverityWarning: |
| 78 | return rtc::LS_WARNING; |
| 79 | case RTCLoggingSeverityError: |
| 80 | return rtc::LS_ERROR; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | @end |