logging: support date modifiers in log filenames

Allow log filenames to contain date modifiers, e.g.:

  - eve-log:
    filename: eve-%Y-%m-%d-%H:%M:%S.json
pull/2655/head
Mats Klepsland 10 years ago committed by Victor Julien
parent bc480fa8c3
commit db6c80fd8e

@ -160,6 +160,26 @@ static int SCLogFileWrite(const char *buffer, int buffer_len, LogFileCtx *log_ct
return ret;
}
/** \brief generate filename based on pattern
* \param pattern pattern to use
* \retval char* on success
* \retval NULL on error
*/
static char *SCLogFilenameFromPattern(const char *pattern)
{
char *filename = SCMalloc(PATH_MAX);
if (filename == NULL) {
return NULL;
}
int rc = SCTimeToStringPattern(time(NULL), pattern, filename, PATH_MAX);
if (rc != 0) {
return NULL;
}
return filename;
}
static void SCLogFileClose(LogFileCtx *log_ctx)
{
if (log_ctx->fp)
@ -178,25 +198,31 @@ SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode)
{
FILE *ret = NULL;
char *filename = SCLogFilenameFromPattern(path);
if (filename == NULL) {
return NULL;
}
if (ConfValIsTrue(append_setting)) {
ret = fopen(path, "a");
ret = fopen(filename, "a");
} else {
ret = fopen(path, "w");
ret = fopen(filename, "w");
}
if (ret == NULL) {
SCLogError(SC_ERR_FOPEN, "Error opening file: \"%s\": %s",
path, strerror(errno));
filename, strerror(errno));
} else {
if (mode != 0) {
int r = chmod(path, mode);
int r = chmod(filename, mode);
if (r < 0) {
SCLogWarning(SC_WARN_CHMOD, "Could not chmod %s to %u: %s",
path, mode, strerror(errno));
filename, mode, strerror(errno));
}
}
}
SCFree(filename);
return ret;
}

@ -478,3 +478,37 @@ int SCStringPatternToTime (char *string, char **patterns, int num_patterns,
return 0;
}
/**
* \brief Convert epoch time to string pattern.
*
* This function converts epoch time to a string based on a pattern.
*
* \param epoch Epoch time.
* \param pattern String pattern.
* \param str Formated string.
* \param size Size of allocated string.
*
* \retval 0 on success.
* \retval 1 on failure.
*/
int SCTimeToStringPattern (time_t epoch, const char *pattern, char *str, size_t size)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
struct tm *tp = (struct tm *)SCLocalTime(epoch, &tm);
char buffer[PATH_MAX] = { 0 };
if (unlikely(tp == NULL)) {
return 1;
}
int r = strftime(buffer, sizeof(buffer), pattern, tp);
if (r == 0) {
return 1;
}
strlcpy(str, buffer, size);
return 0;
}

@ -58,6 +58,8 @@ void CreateFormattedTimeString(const struct tm *t, const char * fmt, char *str,
time_t SCMkTimeUtc(struct tm *tp);
int SCStringPatternToTime(char *string, char **patterns,
int num_patterns, struct tm *time);
int SCTimeToStringPattern (time_t epoch, const char *pattern, char *str,
size_t size);
#endif /* __UTIL_TIME_H__ */

Loading…
Cancel
Save