Skip to content

Commit 6da5b5d

Browse files
committed
simplify color iovec construct
1 parent e03fd19 commit 6da5b5d

1 file changed

Lines changed: 21 additions & 20 deletions

File tree

common/alog.cpp

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
#include <initializer_list>
1817
#ifdef _WIN64
1918
#define _POSIX_C_SOURCE 1
2019
#endif
@@ -37,41 +36,43 @@ using namespace std;
3736

3837
static struct tm alog_time = {0};
3938

40-
#define ALOG_COLOR_RESET "\033[0m"
39+
struct iovec_str : iovec {
40+
template <size_t N>
41+
constexpr iovec_str(const char (&s)[N])
42+
: iovec{const_cast<char*>(s), N - 1} {}
43+
constexpr iovec_str(const char* s, size_t n)
44+
: iovec{const_cast<char*>(s), n} {}
45+
};
46+
47+
constexpr static iovec_str alog_color_reset("\033[0m");
4148

4249
class BaseLogOutput : public ILogOutput {
4350
public:
4451
uint64_t throttle = -1UL;
4552
uint64_t count = 0;
4653
time_t ts = 0;
4754
int log_file_fd;
48-
struct iovec level_prefix[ALOG_AUDIT + 1];
55+
iovec_str level_prefix[ALOG_AUDIT + 1];
4956

5057
constexpr BaseLogOutput(int fd = 0)
5158
: log_file_fd(fd),
52-
level_prefix{
53-
{(void*)ALOG_COLOR_DARKGRAY, sizeof(ALOG_COLOR_DARKGRAY) - 1},
54-
{(void*)ALOG_COLOR_LIGHTGRAY, sizeof(ALOG_COLOR_LIGHTGRAY) - 1},
55-
{(void*)ALOG_COLOR_YELLOW, sizeof(ALOG_COLOR_YELLOW) - 1},
56-
{(void*)ALOG_COLOR_RED, sizeof(ALOG_COLOR_RED) - 1},
57-
{(void*)ALOG_COLOR_MAGENTA, sizeof(ALOG_COLOR_MAGENTA) - 1},
58-
{(void*)ALOG_COLOR_CYAN, sizeof(ALOG_COLOR_CYAN) - 1},
59-
{(void*)ALOG_COLOR_GREEN, sizeof(ALOG_COLOR_GREEN) - 1},
60-
} {}
59+
level_prefix{ALOG_COLOR_DARKGRAY, ALOG_COLOR_LIGHTGRAY,
60+
ALOG_COLOR_YELLOW, ALOG_COLOR_RED,
61+
ALOG_COLOR_MAGENTA, ALOG_COLOR_CYAN,
62+
ALOG_COLOR_GREEN} {}
6163

6264
void set_level_color(int level, const char* color, size_t len) override {
6365
if (level < 0 || level > ALOG_AUDIT) return;
64-
level_prefix[level] = {(void*)color, len};
66+
level_prefix[level] = {color, len};
6567
}
6668

6769
void write(int level, const char* begin, const char* end) override {
68-
struct iovec iov[3] = {
69-
level_prefix[level],
70-
{
71-
.iov_base = (void*)begin,
72-
.iov_len = (size_t)(end - begin),
73-
},
74-
{(void*)ALOG_COLOR_RESET, sizeof(ALOG_COLOR_RESET) - 1}};
70+
struct iovec iov[3] = {level_prefix[level],
71+
{
72+
.iov_base = (void*)begin,
73+
.iov_len = (size_t)(end - begin),
74+
},
75+
alog_color_reset};
7576
std::ignore = ::writev(log_file_fd, iov, 2 + !!iov[0].iov_len);
7677
throttle_block();
7778
}

0 commit comments

Comments
 (0)