// $Id: Logger.cc,v 1.12 2002/10/13 21:12:02 vern Exp $
//
// Copyright (c) 1996, 1997, 1998, 1999, 2002
//      The Regents of the University of California.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that: (1) source code distributions
// retain the above copyright notice and this paragraph in its entirety, (2)
// distributions including binary code include the above copyright notice and
// this paragraph in its entirety in the documentation or other materials
// provided with the distribution, and (3) all advertising materials mentioning
// features or use of this software display the following acknowledgement:
// ``This product includes software developed by the University of California,
// Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
// the University nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

#include <stdlib.h>
#include <math.h>
#include <syslog.h>

#include "config.h"
#include "File.h"
#include "Logger.h"

#ifdef SYSLOG_INT
extern "C" {
int openlog(const char* ident, int logopt, int facility);
int syslog(int priority, const char* message_fmt, ...);
int closelog();
}
#endif

Logger::Logger(const char* name, BroFile* arg_f)
	{
	openlog(name, 0, LOG_LOCAL5);
	f = arg_f;
	enabled = 1;
	}

Logger::~Logger()
	{
	closelog();
	Unref(f);
	}

void Logger::Log(const char* msg)
	{
	int has_timestamp = fabs(atof(msg) - network_time) <= 30.0;

	if ( enabled )
		{
		const char* sub_msg = msg;
		if ( has_timestamp )
			{
			// Don't include the timestamp in the logging,
			// as it gets tacked on by syslog anyway.
			sub_msg = strchr(sub_msg, ' ');
			if ( sub_msg )
				++sub_msg;	// skip over ' '
			else
				sub_msg = msg;
			}

		syslog(LOG_NOTICE, "%s", sub_msg);
		}

	if ( f && f->File() )
		{
		if ( has_timestamp )
			fprintf(f->File(), "%s\n", msg);
		else
			fprintf(f->File(), "%.6f %s\n", network_time, msg);

		fflush(f->File());
		}
	}

void Logger::Describe(ODesc* d) const
	{
	d->AddSP("logger");
	f->Describe(d);
	}
