summaryrefslogtreecommitdiff
path: root/src/log-file.c
blob: edf5ac853ca395b876cd413d4df08477b47e9f0a (plain)
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
/*
 * Copyright (C) 2015 Alexandros Frantzis
 * Author: Alexandros Frantzis <alexandros.frantzis@canonical.com>
 *
 * This program 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 3 of the License, or (at your option) any later
 * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
 * license.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

#include "log-file.h"

int
log_file_open (const gchar *log_filename, LogMode log_mode)
{
    int open_flags = O_WRONLY | O_CREAT;
    int log_fd;

    if (log_mode == LOG_MODE_BACKUP_AND_TRUNCATE)
    {
        /* Move old file out of the way */
        g_autofree gchar *old_filename = NULL;

        old_filename = g_strdup_printf ("%s.old", log_filename);
        rename (log_filename, old_filename);

        open_flags |= O_TRUNC;
    }
    else if (log_mode == LOG_MODE_APPEND)
    {
        /* Keep appending to it */
        open_flags |= O_APPEND;
    }
    else
    {
        g_warning ("Failed to open log file %s: invalid log mode %d specified",
                   log_filename, log_mode);
        return -1;
    }

    /* Open file and log to it */
    log_fd = open (log_filename, open_flags, 0600);
    if (log_fd < 0)
        g_warning ("Failed to open log file %s: %s", log_filename, g_strerror (errno));

    return log_fd;
}