• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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 
16 #ifndef JSVM_LOG_H
17 #define JSVM_LOG_H
18 #include <fstream>
19 #include <iostream>
20 #include <sstream>
21 
22 #include "platform/platform.h"
23 
24 namespace jsvm {
25 class LogStream : public std::stringstream {
26 public:
LogStream()27     LogStream() : std::stringstream() {}
28 
29     virtual ~LogStream() = default;
30 };
31 
32 class LogConsole : public LogStream {
33 public:
LogConsole(platform::OS::LogLevel level)34     explicit LogConsole(platform::OS::LogLevel level) : LogStream(), level(level) {}
35 
~LogConsole()36     ~LogConsole() override
37     {
38         platform::OS::PrintString(level, str().c_str());
39     }
40 
41 private:
42     platform::OS::LogLevel level;
43 };
44 
45 class LogFile : public LogStream {
46 public:
LogFile(const char * filename)47     explicit LogFile(const char* filename) : file(filename, std::ios::app) {};
48 
~LogFile()49     ~LogFile() override
50     {
51         file << str() << std::endl;
52     }
53 
54 private:
55     std::ofstream file;
56 };
57 
58 class LogInfo : public LogConsole {
59 public:
LogInfo()60     LogInfo() : LogConsole(platform::OS::LogLevel::LOG_INFO) {}
61 };
62 
63 class LogError : public LogConsole {
64 public:
LogError()65     LogError() : LogConsole(platform::OS::LogLevel::LOG_ERROR) {}
66 };
67 
68 class LogFatal : public LogConsole {
69 public:
LogFatal()70     LogFatal() : LogConsole(platform::OS::LogLevel::LOG_FATAL) {}
71 };
72 } // namespace jsvm
73 
74 // Support LOG(Info), LOG(Error), LOG(Fatal)
75 #define LOG(level) jsvm::Log##level()
76 
77 // Print Log to file
78 #define LOG_FILE(filename) jsvm::LogFile(filename)
79 #endif