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

aremmell / libsir / 620

09 Sep 2023 07:00PM UTC coverage: 94.508% (-0.3%) from 94.832%
620

push

gitlab-ci

johnsonjh
Merge branch 'master' into write-async

64 of 64 new or added lines in 7 files covered. (100.0%)

3149 of 3332 relevant lines covered (94.51%)

591509.16 hits per line

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

80.43
/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

32
void report_error(void);
33

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

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

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

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

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

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

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

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

83
    /* Initialize libsir. */
84
    if (!sir_init(&si)) {
34✔
85
        report_error();
×
86
        return EXIT_FAILURE;
×
87
    }
88

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

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

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

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

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

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

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

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

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

133
    /*
134
     * Let's decide we better set up logging to the system logger; things seem
135
     * 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

144
#if !defined(SIR_NO_SYSTEM_LOGGERS)
145
    if (!sir_syslogid(appname))
27✔
146
        report_error();
×
147

148
    if (!sir_syslogopts(SIRO_NOPID))
27✔
149
        report_error();
×
150

151
    if (!sir_sysloglevels(SIRL_ERROR | SIRL_CRIT | SIRL_EMERG))
27✔
152
        report_error();
×
153
#endif
154

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

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

163
    (void)sir_debug("Begin server shutdown.");
34✔
164
    (void)sir_debug("If this was real, we would be exiting with code %d now!", 1);
34✔
165

166
    /* Deregister (and close) the log file. */
167
    if (fileid && !sir_remfile(fileid))
34✔
168
        report_error();
×
169

170
    /*
171
     * Now, you can examine the terminal output, libsir-example.log, and
172
     * syslog to ensure that the library operated as expected.
173
     *
174
     * The last thing we have to do is uninitialize libsir by calling sir_cleanup().
175
     */
176
    if (!sir_cleanup())
34✔
177
        report_error();
×
178

179
    return EXIT_SUCCESS;
31✔
180
}
181

182
/**
183
 * Prints the last libsir error to stderr.
184
 */
185
void report_error(void) {
2✔
186
    char message[SIR_MAXERROR] = {0};
2✔
187
    uint16_t code              = sir_geterror(message);
2✔
188
    (void)fprintf(stderr, "libsir error: (%"PRIu16", %s)\n", code, message);
2✔
189
}
2✔
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