• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

aremmell / libsir / 1201

30 Oct 2023 12:42AM UTC coverage: 95.477%. Remained the same
1201

Pull #346

gitlab-ci

johnsonjh
Appease YAML linting

Signed-off-by: Jeffrey H. Johnson <trnsz@pobox.com>
Pull Request #346: Stricter SPDX compliance

3863 of 4046 relevant lines covered (95.48%)

502932.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.88
/example/example.c
1
/**
2
 * @file example.c
3
 *
4
 * A simple demonstration of initialization, configuration, and basic usage of
5
 * libsir.
6
 *
7
 * @author    Ryan M. Lederman \<lederman@gmail.com\>
8
 * @date      2018-2023
9
 * @version   2.2.4
10
 * @copyright The MIT License (MIT)
11
 *
12
 * -----------------------------------------------------------------------------
13
 *
14
 * SPDX-License-Identifier: MIT
15
 *
16
 * Copyright (c) 2018-2023 Ryan M. Lederman <lederman@gmail.com>
17
 * Copyright (c) 2023 Jeffrey H. Johnson <trnsz@pobox.com>
18
 *
19
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 * this software and associated documentation files (the "Software"), to deal in
21
 * the Software without restriction, including without limitation the rights to
22
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 * the Software, and to permit persons to whom the Software is furnished to do so,
24
 * subject to the following conditions:
25
 *
26
 * The above copyright notice and this permission notice shall be included in all
27
 * copies or substantial portions of the Software.
28
 *
29
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 *
36
 * -----------------------------------------------------------------------------
37
 */
38

39
#include "sir.h"
40
#include "sir/helpers.h"
41
#include "sir/internal.h"
42

43
int report_error(void);
44
void report_warning(const char* warning);
45

46
/**
47
 * @brief This is a basic example of initializing and configuring libsir for use.
48
 *
49
 * @note You can build this command-line app yourself using `make example` or the
50
 * Visual Studio [Code] project files.
51
 *
52
 * When the program is finished running, you can see the output in the console,
53
 * and examine the contents of 'libsir-example.log' in the current working
54
 * directory.
55
 *
56
 * @returns EXIT_SUCCESS if execution completes successfully, or EXIT_FAILURE
57
 * if an error occurs.
58
 */
59
int main(void) {
35✔
60
    /*
61
     * Instantiate the libsir initialization struct and customize the configuration.
62
     *
63
     * NOTE: It is not necessary to retain this structure in memory;
64
     * libsir makes a copy of it before returning from ::sir_init.
65
     */
66

67
    sirinit si;
68
    if (!sir_makeinit(&si))
35✔
69
        return report_error();
×
70

71
    /* Levels for stdout: send debug, information, warning, and notice there. */
72
    si.d_stdout.levels = SIRL_DEBUG | SIRL_INFO | SIRL_WARN | SIRL_NOTICE;
35✔
73

74
    /* Options for stdout: don't show the timestamp, hostname, or thread ID. */
75
    si.d_stdout.opts = SIRO_NOTIME | SIRO_NOHOST | SIRO_NOTID;
35✔
76

77
    /* Levels for stderr: send error and above there. */
78
    si.d_stderr.levels = SIRL_ERROR | SIRL_CRIT | SIRL_ALERT | SIRL_EMERG;
35✔
79

80
    /* Options for stderr: don't show the timestamp, hostname, or thread ID. */
81
    si.d_stderr.opts = SIRO_NOTIME | SIRO_NOHOST | SIRO_NOTID;
35✔
82

83
    /* Levels for the system logger: don't send any output there. */
84
    si.d_syslog.levels = SIRL_NONE;
35✔
85

86
    /* Options for the system logger: use the default value. */
87
    si.d_syslog.opts = SIRO_DEFAULT;
35✔
88

89
    /* Configure a name to associate with our output. */
90
    static const char* appname = "MyFooServer";
91
    (void)_sir_strncpy(si.name, SIR_MAXNAME, appname, strnlen(appname, SIR_MAXNAME));
35✔
92

93
    /* Initialize libsir. */
94
    if (!sir_init(&si))
35✔
95
        return report_error();
×
96

97
    /* Set a friendly name for the current thread. */
98
    static const char* thread_name = "example[main]";
99
    (void)_sir_setthreadname(thread_name);
35✔
100

101
    /*
102
     * Configure and add a log file; don't log the process name or hostname,
103
     * and send all levels there.
104
     */
105

106
    sirfileid fileid = sir_addfile("libsir-example.log", SIRL_ALL, SIRO_NONAME | SIRO_NOHOST);
35✔
107
    if (0 == fileid)
35✔
108
        return report_error();
2✔
109

110
    /*
111
     * Ready to start logging. The messages passed to sir_debug() will be sent
112
     * to all destinations registered for the ::SIRL_DEBUG level. In our example,
113
     * that is stdout and 'libsir-example.log'.
114
     */
115

116
    /* Notice that it is not necessary to include a newline */
117
    (void)sir_debug("Reading config file %s...", "/usr/local/myapp/myapp.conf");
33✔
118

119
    /* Pretend to read a config file */
120
    (void)sir_debug("Config file successfully parsed; connecting to database...");
33✔
121

122
    /* Pretend to connect to a database */
123
    (void)sir_debug("Database connection established.");
33✔
124
    (void)sir_debug("Binding a TCP socket to interface '%s'"
33✔
125
                    " (IPv4: %s) on port %u and listening for connections...",
126
                    "eth0", "120.22.140.8", 5500);
127

128
    /*
129
     * Log a message for each of the remaining severity levels. Only up to
130
     * 'notice' will the messages be emitted from stdout; the rest will come from
131
     * stderr.
132
     */
133

134
    (void)sir_info("MyFooServer v%d.%d.%d (amd64) started successfully in %.2fsec.",
33✔
135
                   2, 9, 4, (double)1.94f);
136

137
    (void)sir_notice("Client at %s:%u (username: %s) failed 5 authentication attempts!",
33✔
138
                     "210.10.54.3", 43113, "bob");
139

140
    (void)sir_warn("Detected downgraded link speed on %s: last transfer rate: %.1f KiB/s",
33✔
141
                   "eth0", (double)219.4f);
142

143
    /* Hmm, what else could go wrong... */
144
    (void)sir_error("Failed to synchronize with node pool.846.myfooserver.io! Error:"
33✔
145
                    " %s", "connection reset by peer. Retry in 30sec");
146

147
    /*
148
     * We better set up logging to the system logger; things seem to be going poorly.
149
     *
150
     * Set up an identity, some options, and register for error and higher.
151
     *
152
     * NOTE: If this platform does not have a supported system logger, or the
153
     * SIR_NO_SYSTEM_LOGGERS preprocessor define was set when libsir was
154
     * compiled, these calls will fail and have no effect.
155
     */
156

157
    if (!sir_syslogid(appname))
33✔
158
        report_warning("Failed to set system logger ID");
7✔
159

160
    if (!sir_syslogopts(SIRO_NOPID))
33✔
161
        report_warning("Failed to set system logger options");
7✔
162

163
    if (!sir_sysloglevels(SIRL_ERROR | SIRL_CRIT | SIRL_ALERT | SIRL_EMERG))
33✔
164
        report_warning("Failed to set system logger levels");
7✔
165

166
    /* Okay, syslog should be configured now. Continue executing. */
167
    (void)sir_crit("Database query failure! Ignoring incoming client requests while"
33✔
168
                   " the database is analyzed and repaired...");
169

170
    /* Things just keep getting worse for this poor sysadmin. */
171
    (void)sir_alert("Database repair attempt unsuccessful! Error: %s", "<unknown>");
33✔
172
    (void)sir_emerg("Unable to process client requests for %s! Restarting...", "4m52s");
33✔
173

174
    (void)sir_debug("Begin server shutdown.");
33✔
175
    (void)sir_debug("If this was real, we would be exiting with code %d now!", 1);
33✔
176

177
    /* Deregister (and close) the log file. */
178
    if (!sir_remfile(fileid))
33✔
179
        report_warning("Failed to deregister log file");
×
180

181
    /*
182
     * Now, you can examine the terminal output, libsir-example.log, and
183
     * syslog to ensure that the library operated as expected.
184
     *
185
     * The last thing we have to do is uninitialize libsir by calling sir_cleanup().
186
     */
187

188
    return sir_cleanup() ? EXIT_SUCCESS : report_error();
33✔
189
}
190

191
/**
192
 * @brief Prints the last libsir error to stderr.
193
 *
194
 * @returns EXIT_SUCCESS if execution completes successfully, or
195
 *          EXIT_FAILURE if an error occurs.
196
 */
197
int report_error(void) {
2✔
198
    char message[SIR_MAXERROR] = {0};
2✔
199
    (void)sir_geterror(message);
2✔
200
    (void)fprintf(stderr, "\x1b[31mlibsir error: %s\x1b[0m\n", message);
2✔
201
    return EXIT_FAILURE;
2✔
202
}
203

204
/**
205
 * @brief Prints a warning message along with the last libsir error to stderr.
206
 *
207
 * @param warning The warning message text.
208
 */
209
void report_warning(const char* warning) {
21✔
210
    if (_sir_validstrnofail(warning)) {
21✔
211
        char message[SIR_MAXERROR] = {0};
21✔
212
        (void)sir_geterror(message);
21✔
213
        (void)fprintf(stderr, "\x1b[33m%s! libsir error: %s\x1b[0m\n", warning, message);
21✔
214
    }
215
}
21✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc