P4C
The P4 Compiler
Loading...
Searching...
No Matches
p4tools/common/lib/logging.h
1/*
2 * SPDX-FileCopyrightText: 2023 The P4 Language Consortium
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7#ifndef BACKENDS_P4TOOLS_COMMON_LIB_LOGGING_H_
8#define BACKENDS_P4TOOLS_COMMON_LIB_LOGGING_H_
9
10#include <filesystem>
11#include <optional>
12#include <ostream>
13#include <string>
14#include <type_traits>
15#include <utility>
16
17#include "lib/format.h"
18#include "lib/log.h"
19
20namespace P4::P4Tools {
21
22namespace detail {
23
24// Logging uses operator<<, including overloads for trace events and pointers.
25// Keep that behavior instead of the diagnostic helpers' toString/dbprint dispatch.
26template <typename T>
28 const T &value;
29 friend std::ostream &operator<<(std::ostream &out, const LogArgument &arg) {
30 return out << arg.value;
31 }
32};
33
34template <typename T>
35decltype(auto) logArgument(const T &arg) {
36 if constexpr (std::is_arithmetic_v<T>) {
37 return arg;
38 } else {
39 return LogArgument<T>{arg};
40 }
41}
42
43} // namespace detail
44
47// https://stackoverflow.com/a/25859856
48template <typename... Arguments>
49void printFeature(const std::string &label, int level, const std::string &fmt,
50 Arguments &&...args) {
51 // Do not print logging messages when logging is not enabled.
52 if (!Log::fileLogLevelIsAtLeast(label.c_str(), level)) {
53 return;
54 }
55
56 LOG_FEATURE(label.c_str(), level,
57 createFormattedMessage(fmt.c_str(), detail::logArgument(args)...));
58}
59
62template <typename... Arguments>
63void printInfo(const std::string &fmt, Arguments &&...args) {
64 printFeature("tools_info", 4, fmt, std::forward<Arguments>(args)...);
65}
66
70template <typename... Arguments>
71void printDebug(const std::string &fmt, Arguments &&...args) {
72 printFeature("tools_debug", 4, fmt, std::forward<Arguments>(args)...);
73}
74
77
80
83void printPerformanceReport(const std::optional<std::filesystem::path> &basePath = std::nullopt);
84
85} // namespace P4::P4Tools
86
87#endif /* BACKENDS_P4TOOLS_COMMON_LIB_LOGGING_H_ */
Definition common/compiler/compiler_result.cpp:7
void enablePerformanceLogging()
Enable printing of timing reports.
Definition common/lib/logging.cpp:18
void enableInformationLogging()
Enable the printing of basic run information.
Definition common/lib/logging.cpp:16
void printDebug(const std::string &fmt, Arguments &&...args)
Definition p4tools/common/lib/logging.h:71
void printFeature(const std::string &label, int level, const std::string &fmt, Arguments &&...args)
Definition p4tools/common/lib/logging.h:49
void printInfo(const std::string &fmt, Arguments &&...args)
Definition p4tools/common/lib/logging.h:63
void printPerformanceReport(const std::optional< std::filesystem::path > &basePath)
Definition common/lib/logging.cpp:20
Definition p4tools/common/lib/logging.h:27