summaryrefslogtreecommitdiff
path: root/src/coreclr/hosts/coreconsole/logger.cpp
blob: 7c13c9b5473be8d8c4106f509ae1bd715174ce32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#include <stdio.h>
#include <windows.h>
#include <Logger.h>
#include "palclr.h"

void Logger::Enable() {
    m_isEnabled = true;
}

void Logger::Disable() {
    m_isEnabled = false;
}

void print(const wchar_t *val) {
    // If val is longer than 2048 characters, wprintf will refuse to print it.
    // So write it in chunks.

    const size_t chunkSize = 1024;

    wchar_t chunk[chunkSize];

    auto valLength = ::wcslen(val);

    for (size_t i = 0 ; i < valLength ; i += chunkSize) {

        ::wcsncpy_s(chunk, chunkSize, val + i, _TRUNCATE);

        ::wprintf(W("%s"), chunk);
    }
}

Logger& Logger::operator<< (bool val) {
    if (m_isEnabled) {
        if (val) {
            EnsurePrefixIsPrinted();
            print(W("true"));
        } else {
            EnsurePrefixIsPrinted();
            print(W("false"));
        }
    }
    return *this;
}

Logger& Logger::operator<< (int val) {

    if (m_isEnabled) {
        EnsurePrefixIsPrinted();
		::wprintf(W("%d"), val);
    }

    return *this;
}

#ifdef _MSC_VER
Logger& Logger::operator<< (long val) {
    if (m_isEnabled) {
        EnsurePrefixIsPrinted();
        ::wprintf(W("%d"), val);
    }
    return *this;
}

Logger& Logger::operator<< (unsigned long val) {
    if (m_isEnabled) {
        EnsurePrefixIsPrinted();
        ::wprintf(W("%d"), val);
    }
    return *this;
}
#endif

Logger& Logger::operator<< (const wchar_t *val) {
    if (m_isEnabled) {
        EnsurePrefixIsPrinted();
        print(val);
    }
    return *this;
}

Logger& Logger::operator<< (Logger& ( *pf )(Logger&)) {
    if (m_isEnabled) {
        return pf(*this);
    } else {
        return *this;
    }
}

void Logger::EnsurePrefixIsPrinted() {
    if (this->m_isEnabled && this->m_prefixRequired) {
        print(W(" HOSTLOG: "));
        m_prefixRequired = false;
    }
}

// Manipulators

// Newline
Logger& Logger::endl (Logger& log) {
    if (log.m_isEnabled) {
        log.EnsurePrefixIsPrinted();
        print(W("\r\n"));
        log.m_prefixRequired = true;
        log.m_formatHRESULT = false;
    }
    return log;
}