1 /* file_appender - a dumb log appender which simply prints to a file */
3 /* Copyright (c) 2007-2019. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
9 #include "src/internal_config.h"
10 #include "src/xbt/log_private.hpp"
11 #include "xbt/sysdep.h"
16 static void append_file(xbt_log_appender_t this_, char *str) {
17 fputs(str, (FILE *) this_->data);
20 static void free_(xbt_log_appender_t this_) {
21 if (this_->data != stderr)
22 fclose(static_cast<FILE*>(this_->data));
25 xbt_log_appender_t xbt_log_appender_file_new(char *arg) {
27 xbt_log_appender_t res = xbt_new0(s_xbt_log_appender_t, 1);
28 res->do_append = &append_file;
31 res->data = (void *) fopen(arg, "w");
32 if (res->data == nullptr)
33 xbt_die("Cannot open file: %s: %s", arg, strerror(errno));
35 res->data = (void *) stderr;
40 struct xbt_log_append2_file_s {
43 int count; //negative for roll
46 typedef struct xbt_log_append2_file_s* xbt_log_append2_file_t;
48 static constexpr const char* APPEND2_END_TOKEN = "\n[End of log]\n";
49 static constexpr const char* APPEND2_END_TOKEN_CLEAR = "\n ";
51 static void open_append2_file(xbt_log_append2_file_t data){
55 data->file= fopen(data->filename, "w");
56 if (data->file == nullptr)
57 xbt_die("Cannot open file: %s: %s", data->filename, strerror(errno));
59 fputs(APPEND2_END_TOKEN_CLEAR,data->file);
60 fseek(data->file,0,SEEK_SET);
67 char* pre=xbt_strdup(data->filename);
68 char* sep=strchr(pre,'%');
73 snprintf(newname,511,"%s%i%s",pre,data->count,post);
75 data->file= fopen(newname, "w");
76 if (data->file == nullptr)
77 xbt_die("Cannot open file: %s: %s", newname, strerror(errno));
82 static void append2_file(xbt_log_appender_t this_, char *str) {
83 xbt_log_append2_file_t d=(xbt_log_append2_file_t) this_->data;
85 if(ftell(d->file)>=d->limit) {
90 fputs(APPEND2_END_TOKEN,d->file);
91 fseek(d->file,-((signed long)strlen(APPEND2_END_TOKEN)),SEEK_CUR);
95 static void free_append2_(xbt_log_appender_t this_)
97 xbt_log_append2_file_t data = static_cast<xbt_log_append2_file_t>(this_->data);
100 xbt_free(data->filename);
105 //syntax is <maxsize>:<filename>
106 //If roll is 0, use split files, otherwise, use roll file
107 //For split, replace % in the file by the current count
108 xbt_log_appender_t xbt_log_appender2_file_new(char *arg,int roll) {
110 xbt_log_appender_t res = xbt_new0(s_xbt_log_appender_t, 1);
111 res->do_append = &append2_file;
112 res->free_ = &free_append2_;
113 xbt_log_append2_file_t data = xbt_new0(struct xbt_log_append2_file_s, 1);
115 char* buf=xbt_strdup(arg);
116 char* sep=strchr(buf,':');
117 xbt_assert(sep != nullptr);
118 data->filename=xbt_strdup(sep+1);
121 data->limit=strtol(buf,&endptr,10);
122 xbt_assert(endptr[0]=='\0', "Invalid buffer size: %s", buf);
128 open_append2_file(data);