File: log.c

package info (click to toggle)
neverball 1.6.0%2Bgit20180603-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 152,384 kB
  • sloc: ansic: 27,402; makefile: 454; cpp: 208; xml: 177; sh: 161
file content (98 lines) | stat: -rw-r--r-- 2,200 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2014 Neverball authors
 *
 * NEVERBALL is  free software; you can redistribute  it and/or modify
 * it under the  terms of the GNU General  Public License as published
 * by the Free  Software Foundation; either version 2  of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
 * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
 * General Public License for more details.
 */

#include <stdio.h>
#include <stdlib.h>

#include "log.h"
#include "common.h"
#include "version.h"
#include "fs.h"

static char    log_header[MAXSTR];
static fs_file log_fp;

/*---------------------------------------------------------------------------*/

void log_printf(const char *fmt, ...)
{
    char *str;
    int len;

    va_list ap;

    va_start(ap, fmt);
    len = 1 + vsnprintf(NULL, 0, fmt, ap);
    va_end(ap);

    if ((str = malloc(len)))
    {
        va_start(ap, fmt);
        vsnprintf(str, len, fmt, ap);
        va_end(ap);

        fputs(str, stderr);

        if (log_fp)
        {
            /* These are printfs to get us CRLF conversion. */

            if (log_header[0])
            {
                fs_printf(log_fp, "%s\n", log_header);
                log_header[0] = 0;
            }

            fs_printf(log_fp, "%s", str);

            fs_flush(log_fp);
        }

        free(str);
    }
}

/*---------------------------------------------------------------------------*/

void log_init(const char *name, const char *path)
{
    if (!log_fp)
    {
        if ((log_fp = fs_open_append(path)))
        {
            /* Printed on first message. */

            sprintf(log_header, "%s - %s %s",
                    date_to_str(time(NULL)),
                    name, VERSION);
        }
        else
        {
            fprintf(stderr, "Failure to open %s\n", path);
        }
    }
}

void log_quit(void)
{
    if (log_fp)
    {
        fs_close(log_fp);
        log_fp = NULL;

        log_header[0] = 0;
    }
}

/*---------------------------------------------------------------------------*/