Syslog client for mbed-os 5
Fork of logger by
Diff: logger.cpp
- Revision:
- 0:7d428b9b277e
- Child:
- 1:f7e32e99f366
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/logger.cpp Sat Apr 16 08:48:55 2011 +0000 @@ -0,0 +1,95 @@ +/* + * syslog device library + * Copyright (c) 2011 Hiroshi Suga + * Released under the MIT License: http://mbed.org/license/mit + */ + +/** @file logger.cpp + * @brief syslog device (sender/client) + */ + +#include "logger.h" + +static const char mstr[12][4] = {"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + +/** + * @brief init + * @param p_eth EthernetNetIf class + * @param host syslog collctor (server) + */ +logger::logger (EthernetNetIf *p_eth, char *host) { + IpAddr addr; + char name[20]; + + addr = p_eth->getIp(); + sprintf(name, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]); + + logger(p_eth, host, name); +} + +/** + * @brief init + * @param p_eth EthernetNetIf class + * @param host syslog collctor (server) hostname or IP address + * @param myname My hostname or IP address + */ +logger::logger (EthernetNetIf *p_eth, char *host, char *myname) { + int ip0, ip1, ip2, ip3; + + eth = p_eth; + strncpy(ident, myname, sizeof(ident)); + + if (host[0] >= '0' && host[0] <= '9') { + sscanf(host, "%d.%d.%d.%d", &ip0, &ip1, &ip2, &ip3); + remote.setIp(IpAddr(ip0, ip1, ip2, ip3)); + remote.setName(NULL); + } else { + remote.setIp(NULL); + remote.setName(host); + } + remote.setPort(LOG_UDPPORT); + + udpsock = new UDPSocket; + udpsock->bind(Host(eth->getIp(), LOG_UDPPORT)); +} + +/** + * @brief Send the message + * @param tag Process name + * @param content Message + */ +void logger::send (char *tag, char *content) { + send(LOG_NOTICE, LOG_USER, tag, content); +} + +/** + * @brief Send the message + * @param sev Severity + * @param fac Facility + * @param tag Process name + * @param content Message + */ +void logger::send (LOG_SEVERITY sev, LOG_FACILITY fac, char *tag, char *content) { + int pri, len; + time_t ctTime; + struct tm *t; + char logmsg[LOG_LEN]; + + ctTime = time(NULL); + t = localtime(&ctTime); + pri = (fac * 8) | sev; + + sprintf(logmsg, "<%d>%s %2d %02d:%02d:%02d %s ", pri, mstr[t->tm_mon - 1], t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, ident); + + len = strlen(tag); + if (len > 32) len = 32; + strncat(logmsg, tag, len); + + strcat(logmsg, " "); + + len = strlen(content); + if (len > LOG_LEN - strlen(logmsg) - 1) len = LOG_LEN - strlen(logmsg) - 1; + strncat(logmsg, content, len); + + udpsock->sendto(logmsg, strlen(logmsg), &remote); +}