1
0
mirror of https://github.com/pevans/erc-c.git synced 2024-12-01 00:49:46 +00:00
erc-c/src/log.c

64 lines
1.4 KiB
C
Raw Normal View History

2017-11-22 05:24:51 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
2017-12-02 19:05:53 +00:00
#include "log.h"
2017-12-06 22:43:30 +00:00
/*
* This is the file stream we will write to for our logging. It can be
* any number of things, from a literal file on the filesystem, to
* stdout.
*/
2017-11-22 05:24:51 +00:00
static FILE *log_stream = NULL;
2017-12-06 22:43:30 +00:00
/*
* This function will assign the log_stream variable to either a given
* file stream, or if none given, to the default location (which is a
* filename defined by the `LOG_FILENAME` macro).
*/
2017-11-22 05:24:51 +00:00
void
2017-12-06 22:43:30 +00:00
log_open(FILE *stream)
2017-11-22 05:24:51 +00:00
{
2017-12-06 22:43:30 +00:00
// Oh, you're telling _me_ what the stream is? Neat!
if (stream != NULL) {
log_stream = stream;
return;
}
// Oh, well. I'll just open this dang thing.
2017-12-02 19:05:53 +00:00
log_stream = fopen(LOG_FILENAME, "w");
2017-11-22 05:24:51 +00:00
if (log_stream == NULL) {
2017-12-02 19:05:53 +00:00
perror("Couldn't open log file (" LOG_FILENAME ")");
2017-11-22 05:24:51 +00:00
exit(1);
}
}
2017-12-06 22:43:30 +00:00
/*
* Close the file stream we opened (or were given) in `log_open()`.
* Nota bene: if you passed stdout into log_open(), this will actually
* _close_ the stdout stream (!).
*/
2017-11-22 05:24:51 +00:00
void
log_close()
{
if (log_stream != NULL) {
fclose(log_stream);
}
}
2017-12-06 22:43:30 +00:00
/*
* Write to the log stream. This function can accept variable arguments,
* ala `printf()`. There is some support for different log levels, but
* as you may note, we do not use them at present.
*/
2017-11-22 05:24:51 +00:00
void
log_write(int level, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(log_stream, fmt, ap);
fprintf(log_stream, "\n");
va_end(ap);
}