Syslog client for mbed-os 5

Fork of logger by Suga koubou

Logger.cpp

Committer:
Colin Hogben
Date:
2016-10-20
Revision:
6:cf9acc20f954
Parent:
5:641de66579d2

File content as of revision 6:cf9acc20f954:

/*
 * syslog device library
 * Copyright (c) 2011 Hiroshi Suga
 * Copyright (c) 2016 Colin Hogben
 * Released under the MIT License: http://mbed.org/license/mit
 */

/** @file Logger.cpp
 * @brief syslog device (sender/client)
 */

#include "Logger.h"
#include <cstdio>

#ifdef MBED_CONF_LOGGER_LINE_MAX
#define LOG_LEN MBED_CONF_LOGGER_LINE_MAX
#else
#define LOG_LEN 256
#endif

#define LOG_UDPPORT 514

static const char mstr[12][4] = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

Logger::Logger(NetworkInterface *netif, const char *host) {
    _Logger(netif, host, netif->get_ip_address());
}

Logger::Logger(NetworkInterface *netif, const char *host, const char *myname) {
    _Logger(netif, host, myname);
}

void Logger::_Logger(NetworkInterface *netif, const char *host, const char *myname) {
    _remote = SocketAddress(host, LOG_UDPPORT);
    snprintf(_ident, sizeof(_ident), "%s", myname);
    int err = _udpsock.open(netif);
    if (err) error("Cannot open syslog UDP socket");
    _udpsock.bind(LOG_UDPPORT);
}

void Logger::send(const char *tag, const char *content) {
    send(LOG_NOTICE, LOG_USER, tag, content);
}

void Logger::send(LOG_SEVERITY sev, LOG_FACILITY fac, const char *tag, const char *content) {
    char logmsg[LOG_LEN];

    time_t ctTime = time(NULL);  
    struct tm *t = localtime(&ctTime);
    int pri = (fac * 8) | sev;

    snprintf(logmsg, sizeof(logmsg),
             "<%d>%s %2d %02d:%02d:%02d %s %s %s",
             pri,
             mstr[t->tm_mon], t->tm_mday,
             t->tm_hour, t->tm_min, t->tm_sec,
             _ident,
             tag,
             content);
    _udpsock.sendto(_remote, logmsg, strlen(logmsg));
}