1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "lang_id/common/lite_base/compact-logging.h"
18 
19 #include <stdlib.h>
20 
21 #include <iostream>
22 
23 #include "lang_id/common/lite_base/compact-logging-raw.h"
24 
25 #ifndef SAFTM_LOGGING_TAG
26 
27 // Tag inserted in the prefix of the generated log messages.  The user can
28 // override this by defining this macro on the blaze build command-line.
29 #define SAFTM_LOGGING_TAG "saftm"
30 #endif
31 
32 namespace libtextclassifier3 {
33 namespace mobile {
34 namespace internal_logging {
35 
36 namespace {
37 // Returns pointer to beginning of last /-separated token from file_name.
38 // file_name should be a pointer to a zero-terminated array of chars.
39 // E.g., "foo/bar.cc" -> "bar.cc", "foo/" -> "", "foo" -> "foo".
JumpToBasename(const char * file_name)40 const char *JumpToBasename(const char *file_name) {
41   if (file_name == nullptr) {
42     return nullptr;
43   }
44 
45   // Points to the beginning of the last encountered token.
46   const char *last_token_start = file_name;
47   while (*file_name != '\0') {
48     if (*file_name == '/') {
49       // Found token separator.  A new (potentially empty) token starts after
50       // this position.  Notice that if file_name is a valid zero-terminated
51       // string, file_name + 1 is a valid pointer (there is at least one char
52       // after address file_name, the zero terminator).
53       last_token_start = file_name + 1;
54     }
55     file_name++;
56   }
57   return last_token_start;
58 }
59 }  // namespace
60 
LogMessage(LogSeverity severity,const char * file_name,int line_number)61 LogMessage::LogMessage(LogSeverity severity, const char *file_name,
62                        int line_number)
63     : severity_(severity) {
64   stream_ << JumpToBasename(file_name) << ":" << line_number << ": ";
65 }
66 
~LogMessage()67 LogMessage::~LogMessage() {
68   LogSeverity level = severity_;
69   if (level == DFATAL) {
70 #ifdef NDEBUG
71     level = ERROR;
72 #else
73     level = FATAL;
74 #endif
75   }
76   LowLevelLogging(level, /* tag = */ SAFTM_LOGGING_TAG, stream_.message);
77   if (level == FATAL) {
78     exit(1);
79   }
80 }
81 
82 }  // namespace internal_logging
83 }  // namespace mobile
84 }  // namespace nlp_saft
85