2 * UCW Library -- Logging to Files
4 * (c) 1997--2009 Martin Mares <mj@ucw.cz>
5 * (c) 2008 Tomas Gavenciak <gavento@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include "ucw/threads.h"
25 static char *log_name_patt;
26 static int log_params;
27 static int log_filename_size;
28 static int log_switch_nest;
31 do_log_switch(struct tm *tm)
34 char name[log_filename_size];
38 log_filename[0] && !log_params)
42 l = strftime(name, log_filename_size, log_name_patt, tm);
43 if (l < 0 || l >= log_filename_size)
44 die("Error formatting log file name: %m");
45 if (strcmp(name, log_filename))
47 strcpy(log_filename, name);
48 fd = ucw_open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
50 die("Unable to open log file %s: %m", name);
63 time_t tim = time(NULL);
64 return do_log_switch(localtime(&tim));
68 internal_log_switch(struct tm *tm)
75 log_file(const char *name)
86 log_name_patt = xstrdup(name);
87 log_params = !!strchr(name, '%');
88 log_filename_size = strlen(name) + 64; /* 63 is an upper bound on expansion of % escapes */
89 log_filename = xmalloc(log_filename_size);
92 log_switch_hook = internal_log_switch;
103 log_switch_disable(void)
109 log_switch_enable(void)
111 ASSERT(log_switch_nest);
117 /* destructor for standard files */
118 static void ls_fdfile_close(struct log_stream *ls)
126 /* handler for standard files */
127 static int ls_fdfile_handler(struct log_stream* ls, const char *m, uns cat UNUSED)
130 int r = write(ls->idata, m, len);
131 /* TODO: check the errors here? */
137 /* assign log to a file descriptor */
138 /* initialize with the default formatting, does NOT close the descriptor */
139 struct log_stream *ls_fdfile_new(int fd)
141 struct log_stream *ls=log_new_stream();
143 ls->msgfmt=LSFMT_DEFAULT;
144 ls->handler=ls_fdfile_handler;
148 /* open() a file (append mode) */
149 /* initialize with the default formatting */
150 struct log_stream *ls_file_new(const char *path)
152 struct log_stream *ls;
153 int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0666);
156 msg(L_ERROR, "Opening logfile '%s' failed: %m.", path);
159 ls = log_new_stream();
160 ls->name = xstrdup(path);
162 ls->msgfmt = LSFMT_DEFAULT;
163 ls->handler = ls_fdfile_handler;
164 ls->close = ls_fdfile_close;
170 int main(int argc, char **argv)
173 log_file("/proc/self/fd/1");
174 for (int i=1; i<argc; i++)
175 msg(L_INFO, argv[i]);