WriterLog.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/log/WriterLog.h"
  16. #include "util/log/Log_impl.h"
  17. #include "util/CString.h"
  18. #include "io/Writer.h"
  19. #include <stdarg.h>
  20. #include <stdint.h>
  21. #include <stdio.h>
  22. #include <strings.h>
  23. #include <time.h>
  24. struct WriterLog
  25. {
  26. struct Log pub;
  27. struct Writer* writer;
  28. };
  29. static void print(struct Log* genericLog,
  30. enum Log_Level logLevel,
  31. const char* file,
  32. int line,
  33. const char* format,
  34. va_list args)
  35. {
  36. struct WriterLog* log = (struct WriterLog*) genericLog;
  37. char timeAndLevelBuff[64];
  38. time_t now;
  39. time(&now);
  40. snprintf(timeAndLevelBuff, 64, "%u %s ", (uint32_t) now, Log_nameForLevel(logLevel));
  41. Writer_write(log->writer, timeAndLevelBuff, CString_strlen(timeAndLevelBuff));
  42. // Strip the path to make log lines shorter.
  43. //char* lastSlash = CString_strrchr(file, '/');
  44. Writer_write(log->writer, file, CString_strlen(file));
  45. #define Log_BUFFER_SZ 1024
  46. char buff[Log_BUFFER_SZ];
  47. snprintf(buff, Log_BUFFER_SZ, ":%u ", line);
  48. Writer_write(log->writer, buff, CString_strlen(buff));
  49. vsnprintf(buff, Log_BUFFER_SZ, format, args);
  50. size_t length = CString_strlen(buff);
  51. // Some log lines end in \n, others don't.
  52. if (length < Log_BUFFER_SZ && buff[length - 1] != '\n') {
  53. buff[length++] = '\n';
  54. }
  55. Writer_write(log->writer, buff, length > Log_BUFFER_SZ ? Log_BUFFER_SZ : length);
  56. #undef Log_BUFFER_SZ
  57. }
  58. struct Log* WriterLog_new(struct Writer* w, struct Allocator* alloc)
  59. {
  60. return Allocator_clone(alloc, (&(struct WriterLog) {
  61. .pub = {
  62. .print = print
  63. },
  64. .writer = w
  65. }));
  66. }