Syslog client for mbed-os 5

Fork of logger by Suga koubou

logger.cpp

Committer:
Colin Hogben
Date:
2016-10-14
Revision:
4:b51e0614c767
Parent:
3:91ee7ead8536

File content as of revision 4:b51e0614c767:

/*
 * 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>

#define LOG_LEN 256
#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));
}