xref: /openbmc/openpower-hw-diags/util/trace.hpp (revision f3c48d0774d38d859c7ec6236b14547c1b33e570)
1 #pragma once
2 
3 #include <inttypes.h>
4 #include <stdio.h>
5 
6 #include <phosphor-logging/lg2.hpp>
7 
8 #include <cstdarg>
9 
10 #ifndef TEST_TRACE
11 #include <phosphor-logging/log.hpp>
12 #endif
13 
14 namespace trace
15 {
16 
17 /** @brief Information trace (va_list format). */
inf(const char * format,va_list args1)18 inline void inf(const char* format, va_list args1)
19 {
20     // Need to make a copy of the given va_list because we'll be iterating the
21     // list twice with the vnsprintf() calls below.
22     va_list args2;
23     va_copy(args2, args1);
24 
25     int sz = vsnprintf(nullptr, 0, format, args1); // hack to get required size
26     char* msg = new char[sz + 1](); // allocate room for terminating character
27     vsnprintf(msg, sz + 1, format, args2); // print the message
28 
29 #ifdef TEST_TRACE
30     fprintf(stdout, "%s\n", msg);
31 #else
32     phosphor::logging::log<phosphor::logging::level::INFO>(msg);
33 #endif
34 
35     delete[] msg; // clean up
36 }
37 
38 /** @brief Error trace (va_list format). */
err(const char * format,va_list args1)39 inline void err(const char* format, va_list args1)
40 {
41     // Need to make a copy of the given va_list because we'll be iterating the
42     // list twice with the vnsprintf() calls below.
43     va_list args2;
44     va_copy(args2, args1);
45 
46     int sz = vsnprintf(nullptr, 0, format, args1); // hack to get required size
47     char* msg = new char[sz + 1](); // allocate room for terminating character
48     vsnprintf(msg, sz + 1, format, args2); // print the message
49 
50 #ifdef TEST_TRACE
51     fprintf(stderr, "%s\n", msg);
52 #else
53     phosphor::logging::log<phosphor::logging::level::ERR>(msg);
54 #endif
55 
56     delete[] msg; // clean up
57 }
58 
59 /** @brief Information trace (printf format). */
inf(const char * format,...)60 inline void inf(const char* format, ...)
61 {
62     va_list args;
63     va_start(args, format);
64     trace::inf(format, args);
65     va_end(args);
66 }
67 
68 /** @brief Error trace (printf format). */
err(const char * format,...)69 inline void err(const char* format, ...)
70 {
71     va_list args;
72     va_start(args, format);
73     trace::err(format, args);
74     va_end(args);
75 }
76 
77 } // namespace trace
78