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

aremmell / libsir / 900

26 Sep 2023 07:56AM UTC coverage: 95.039% (+0.7%) from 94.307%
900

push

gitlab-ci

web-flow
Improve test coverage (#303)

Going after the low-hanging fruit.

---------

Co-authored-by: Jeffrey H. Johnson <trnsz@pobox.com>

200 of 200 new or added lines in 4 files covered. (100.0%)

3621 of 3810 relevant lines covered (95.04%)

533615.45 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
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
13
 * this software and associated documentation files (the "Software"), to deal in
14
 * the Software without restriction, including without limitation the rights to
15
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
16
 * the Software, and to permit persons to whom the Software is furnished to do so,
17
 * subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
24
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
25
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
26
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
 */
29
#include "sir.h"
30
#include "sir/helpers.h"
31
#include "sir/internal.h"
32

33
int report_error(void);
34
void report_warning(const char* warning);
35

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

60
    /* Levels for stdout: send debug, information, warning, and notice there. */
61
    si.d_stdout.levels = SIRL_DEBUG | SIRL_INFO | SIRL_WARN | SIRL_NOTICE;
34✔
62

63
    /* Options for stdout: don't show the timestamp, hostname, or thread ID. */
64
    si.d_stdout.opts = SIRO_NOTIME | SIRO_NOHOST | SIRO_NOTID;
34✔
65

66
    /* Levels for stderr: send error and above there. */
67
    si.d_stderr.levels = SIRL_ERROR | SIRL_CRIT | SIRL_ALERT | SIRL_EMERG;
34✔
68

69
    /* Options for stderr: don't show the timestamp, hostname, or thread ID. */
70
    si.d_stderr.opts = SIRO_NOTIME | SIRO_NOHOST | SIRO_NOTID;
34✔
71

72
    /* Levels for the system logger: don't send any output there. */
73
    si.d_syslog.levels = SIRL_NONE;
34✔
74

75
    /* Options for the system logger: use the default value. */
76
    si.d_syslog.opts = SIRO_DEFAULT;
34✔
77

78
    /* Configure a name to associate with our output. */
79
    static const char* appname = "MyFooServer";
80
    (void)_sir_strncpy(si.name, SIR_MAXNAME, appname, strnlen(appname, SIR_MAXNAME));
34✔
81

82
    /* Initialize libsir. */
83
    if (!sir_init(&si))
34✔
84
        return report_error();
×
85

86
    /* Set a friendly name for the current thread. */
87
    static const char* thread_name = "example[main]";
88
    (void)_sir_setthreadname(thread_name);
34✔
89

90
    /*
91
     * Configure and add a log file; don't log the process name or hostname,
92
     * and send all levels there.
93
     */
94
    sirfileid fileid = sir_addfile("libsir-example.log", SIRL_ALL, SIRO_NONAME | SIRO_NOHOST);
34✔
95
    if (0 == fileid)
34✔
96
        return report_error();
2✔
97

98
    /*
99
     * Ready to start logging. The messages passed to sir_debug() will be sent
100
     * to all destinations registered for the ::SIRL_DEBUG level. In our example,
101
     * that is stdout and 'libsir-example.log'.
102
     */
103

104
    /* Notice that it is not necessary to include a newline */
105
    (void)sir_debug("Reading config file %s...", "/usr/local/myapp/myapp.conf");
32✔
106

107
    /* Pretend to read a config file */
108
    (void)sir_debug("Config file successfully parsed; connecting to database...");
32✔
109

110
    /* Pretend to connect to a database */
111
    (void)sir_debug("Database connection established.");
32✔
112
    (void)sir_debug("Binding a TCP socket to interface '%s'"
32✔
113
                    " (IPv4: %s) on port %u and listening for connections...",
114
                    "eth0", "120.22.140.8", 5500);
115

116
    /*
117
     * Log a message for each of the remaining severity levels. Only up to
118
     * 'notice' will the messages be emitted from stdout; the rest will come from
119
     * stderr.
120
     */
121
    (void)sir_info("MyFooServer v%d.%d.%d (amd64) started successfully in %.2fsec.",
32✔
122
                   2, 9, 4, (double)1.94f);
123

124
    (void)sir_notice("Client at %s:%u (username: %s) failed 5 authentication attempts!",
32✔
125
                     "210.10.54.3", 43113, "bob");
126

127
    (void)sir_warn("Detected downgraded link speed on %s: last transfer rate: %.1f KiB/s",
32✔
128
                   "eth0", (double)219.4f);
129

130
    /* Hmm, what else could go wrong... */
131
    (void)sir_error("Failed to synchronize with node pool.846.myfooserver.io! Error:"
32✔
132
                    " %s", "connection reset by peer. Retry in 30sec");
133

134
    /*
135
     * We better set up logging to the system logger; things seem to be going poorly.
136
     *
137
     * Set up an identity, some options, and register for error and higher.
138
     *
139
     * NOTE: If this platform does not have a supported system logger, or the
140
     * SIR_NO_SYSTEM_LOGGERS preprocessor define was set when libsir was
141
     * compiled, these calls will fail and have no effect.
142
     */
143
    if (!sir_syslogid(appname))
32✔
144
        report_warning("Failed to set system logger ID");
7✔
145

146
    if (!sir_syslogopts(SIRO_NOPID))
32✔
147
        report_warning("Failed to set system logger options");
7✔
148

149
    if (!sir_sysloglevels(SIRL_ERROR | SIRL_CRIT | SIRL_ALERT | SIRL_EMERG))
32✔
150
        report_warning("Failed to set system logger levels");
7✔
151

152
    /* Okay, syslog should be configured now. Continue executing. */
153
    (void)sir_crit("Database query failure! Ignoring incoming client requests while"
32✔
154
                   " the database is analyzed and repaired...");
155

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

160
    (void)sir_debug("Begin server shutdown.");
32✔
161
    (void)sir_debug("If this was real, we would be exiting with code %d now!", 1);
32✔
162

163
    /* Deregister (and close) the log file. */
164
    if (!sir_remfile(fileid))
32✔
165
        report_warning("Failed to deregister log file");
×
166

167
    /*
168
     * Now, you can examine the terminal output, libsir-example.log, and
169
     * syslog to ensure that the library operated as expected.
170
     *
171
     * The last thing we have to do is uninitialize libsir by calling sir_cleanup().
172
     */
173
    return sir_cleanup() ? EXIT_SUCCESS : report_error();
32✔
174
}
175

176
/**
177
 * Prints the last libsir error to stderr and returns EXIT_FAILURE.
178
 */
179
int report_error(void) {
2✔
180
    char message[SIR_MAXERROR] = {0};
2✔
181
    (void)sir_geterror(message);
2✔
182
    (void)fprintf(stderr, "\x1b[31mlibsir error: %s\x1b[0m\n", message);
2✔
183
    return EXIT_FAILURE;
2✔
184
}
185

186
/**
187
 * Prints a warning message along with the last libsir error to stderr.
188
 */
189
void report_warning(const char* warning) {
21✔
190
    if (_sir_validstrnofail(warning)) {
21✔
191
        char message[SIR_MAXERROR] = {0};
21✔
192
        (void)sir_geterror(message);
21✔
193
        (void)fprintf(stderr, "\x1b[33m%s! libsir error: %s\x1b[0m\n", warning, message);
21✔
194
    }
195
}
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

© 2025 Coveralls, Inc