WriterLog.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #include "util/log/WriterLog.h"
  16. #include "util/log/Log_impl.h"
  17. #include "io/Writer.h"
  18. #include <stdarg.h>
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #define string_strlen
  22. #define string_strrchr
  23. #include "util/platform/libc/string.h"
  24. #include <strings.h>
  25. #include <time.h>
  26. struct WriterLog
  27. {
  28. struct Log pub;
  29. struct Writer* writer;
  30. };
  31. static void print(struct Log* genericLog,
  32. enum Log_Level logLevel,
  33. const char* file,
  34. int line,
  35. const char* format,
  36. va_list args)
  37. {
  38. struct WriterLog* log = (struct WriterLog*) genericLog;
  39. char timeAndLevelBuff[64];
  40. time_t now;
  41. time(&now);
  42. snprintf(timeAndLevelBuff, 64, "%u %s ", (uint32_t) now, Log_nameForLevel(logLevel));
  43. Writer_write(log->writer, timeAndLevelBuff, strlen(timeAndLevelBuff));
  44. // Strip the path to make log lines shorter.
  45. //char* lastSlash = strrchr(file, '/');
  46. Writer_write(log->writer, file, strlen(file));
  47. #define Log_BUFFER_SZ 1024
  48. char buff[Log_BUFFER_SZ];
  49. snprintf(buff, Log_BUFFER_SZ, ":%u ", line);
  50. Writer_write(log->writer, buff, strlen(buff));
  51. vsnprintf(buff, Log_BUFFER_SZ, format, args);
  52. size_t length = strlen(buff);
  53. // Some log lines end in \n, others don't.
  54. if (length < Log_BUFFER_SZ && buff[length - 1] != '\n') {
  55. buff[length++] = '\n';
  56. }
  57. Writer_write(log->writer, buff, length > Log_BUFFER_SZ ? Log_BUFFER_SZ : length);
  58. #undef Log_BUFFER_SZ
  59. }
  60. struct Log* WriterLog_new(struct Writer* w, struct Allocator* alloc)
  61. {
  62. return Allocator_clone(alloc, (&(struct WriterLog) {
  63. .pub = {
  64. .print = print
  65. },
  66. .writer = w
  67. }));
  68. }