LoggerService, mess with logs in written file

Hello fam,

I’m trying to create a logger service for my project to write a file and send it to my server. Through console it writes ok, but when I open the file it is supposed to write … there is a mess with the logs.

I’m using this setup for the app:

Ionic:

   Ionic CLI                     : 6.18.1 
   Ionic Framework               : @ionic/angular 5.9.3
   @angular-devkit/build-angular : 0.901.15
   @angular-devkit/schematics    : 9.1.12
   @angular/cli                  : 9.1.12
   @ionic/angular-toolkit        : 2.3.3

Cordova:

   Cordova CLI       : 10.0.0 (cordova-lib@10.1.0)
   Cordova Platforms : not available
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 18 other plugins)

Here is my code:

import { Injectable } from '@angular/core';
import { File } from '@ionic-native/file/ngx';
import { Device } from '@ionic-native/device/ngx';
@Injectable({
  providedIn: 'root',
})
export class LoggerServiceService {
  nombreLog: string;
  
  constructor(private readonly file: File, private readonly device: Device) {
    const fechaHoy = new Date();
    this.nombreLog =
      'log_' +
      fechaHoy.toLocaleDateString().replace('/', '').replace('/', '') +
      '.log';
  }

  info(mensaje: string) {
    this.log(mensaje, 'INFO');
  }

  error(mensaje: string) {
    this.log(mensaje, 'ERROR');
  }

  log(mensaje: string, tipo: string) {

    const fechaHoraLog = new Date();
    const fec =  fechaHoraLog.toLocaleString();
    const seg = String(fechaHoraLog.getMilliseconds()).padStart(3, '0');

    const msgArray = [];
    msgArray.push(mensaje);

    for (let elemento of msgArray){
      mensaje = `\n${fec},${seg} - ${this.device.uuid} - ${tipo} - ${elemento}`;
      console.log(mensaje);
    }

    this.file.writeFile(this.file.dataDirectory + '/logs', this.nombreLog, mensaje, { append: true, replace: false });
  }

  comprobarFicheroYdirectorioLog(callback) {
    this.file
      .checkDir(this.file.dataDirectory, 'logs')
      .then((result) => {
        const fechaHoy = new Date();
        const nombreLog =
          'log_' +
          fechaHoy.toLocaleDateString().replace('/', '').replace('/', '') +
          '.log';
        this.file
          .checkFile(this.file.dataDirectory, this.nombreLog)
          .then((result) => {
            if (!result) {
              //log no existe por alguna razon pero la funcion no devuelve error, no deberia ocurrir
              this.file
                .createFile(this.file.dataDirectory + '/logs', nombreLog, true)
                .then((result) => {
                  callback();
                });
            }
          })
          .catch((err) => {
            console.log('fichero no existe');
            //no se encuentra el fichero log
            this.file
              .createFile(this.file.dataDirectory + '/logs', nombreLog, true)
              .then((result) => {
                callback();
                console.log(result);
              });
          });
      })
      .catch((err) => {
        console.log('directorio no existe');
        this.file
          .createDir(this.file.dataDirectory, 'logs', false)
          .then((result) => {
            console.log('directorio creado ');
            this.info('Directorio logs creado ');
            this.comprobarFicheroYdirectorioLog(callback);
          })
          .catch((err) => {
            console.log('directorio no creado' + err);
            this.error('Directorio logs no creado');
            callback();
          });
      });
  }
}

And here is what I find when I open the file:

22/4/2022, 11:04:03,525 - e42ab3ff7ff8995c - INFO - PAGINA 1 DELETE -> 613428940,613428942,613428944,613429035
22/4/2022, 11:04:04,030 - e42ab3ff7ff8995c - INFO - Guardando anomalias descargadas
22/4/2022, 11:04:07,587 - e42ab3ff7ff8995c - INFO - Respuesta servidor OK
22/4/2022, 11:04:07,596 - e42ab3ff7ff8995c - INFO - DATOS DESCARGADOS PARA LA PAGINA 2
22/4/2022, 11:04:08,306 - e42ab3ff7ff8995c - INFO - Guardando anomalias descargadas
22/4/2022, 11:04:11,142 - e42ab3ff7ff8995c - INFO - Comienza proceso de UPSERT_1
22/4/2022, 11:04:11,429 - e42ab3ff7ff8995c - INFO - Guardando anomalias descargadas
22/4/2022, 11:04:12,025 - e42ab3ff7ff8995c - INFO - Exito en descarga anomalias Gamad
22/4/2022, 11:04:12,435 - e42ab3ff7ff8995c - INFO - NAVEGACION -> seleccion-elemento
22/4/2022, 11:04:17,289 - e42ab3ff7ff8995c - INFO - file:///data/user/0/iberdrola.distribucion.medisweb.gia.intune.intg/files/
22/4/2022, 11:04:17,333 - e42ab3ff7ff8995c - INFO - [object Object]
22/4/2022, 11:05:54,700 - e42ab3ff7ff8995c - INFO - Se ha creado Maestros.db
22/4/2022, 11:05:56,002 - e42ab3ff7ff8995c - INFO - El numero de version es:  0.1.7
22/4/2022, 11:05:56,339 - e42ab3ff7ff8995c - INFO - Se ha añadido registros en Medisgia.db
22/4/2022, 11:05:56,563 - e42ab3ff7ff8995c - INFO - No hace falta descargar Maestros local
22/4/2022, 11:05:59,571 - e42ab3ff7ff8995c - INFO - Se hace llamada al servidor de descarga de anomalias: sincronizarAnomaliasGamadServiceImpl
22/4/2022, 11:05:59,931 - e42ab3ff7ff8995c - INFO - **PAGINA 0 UPSERT -> No**
**22/4/2**
22/4/2022, 11:05:59,936 - e42ab3ff7ff8995c - INFO - Comienza proceso de DELETE
22/4/2022, 11:06:00,101 - e42ab3ff7ff8995c - INFO - Se hace llamada al servidor de descarga de anomalias: sincronizarAnomaliasGamadServiceImpl
22/4/2022, 11:06:00,116 - e42ab3ff7ff8995c - INFO - Guardando anomalias descargadas
22/4/2022, 11:06:00,349 - e42ab3ff7ff8995c - INFO - DATOS DESCARGADOS PARA LA PA
22/4/2022, 11:06:00,359 - e42ab3ff7ff8995c - INFO - PAGINA 1 INSERT ->  No hay anoma
22/4/2022, 11:06:00,555 - e42ab3ff7ff8995c - INFO - Guardando anomalias descargadas
22/4/2022, 11:06:01,155 - e42ab3ff7ff8995c - INFO - Exito en descarga anomalias Gamad
22/4/2022, 11:06:01,616 - e42ab3ff7ff8995c - INFO - NAVEGACION -> seleccion-elemento

That is just a small example, but I got a lot of badly written lines and there are a lot more missing.

First before pushing the ‘mensaje’ to the msgArray I tried to directly print it like this:

log(mensaje: string, tipo: string) {
    const fechaHoraLog = new Date();
    const fec =  fechaHoraLog.toLocaleString();
    const seg = String(fechaHoraLog.getMilliseconds()).padStart(3, '0');
    mensaje = `\n${fec},${seg} - ${this.device.uuid} - ${tipo} - ${mensaje}`;
    this.file.writeFile(this.file.dataDirectory + '/logs', this.nombreLog, mensaje, { append: true, replace: false });
  }

but it was even worse.

Hope you can help!