2017-01-10 4 views
0

Meine Java-Anwendung CB ruft Daten aus einer Datenbank ab, z. B. "Fall 1". Jedes Mal, CB beginnt, ist erstellt eine Log-Datei:2 frühere Versionen einer Protokolldatei beibehalten

Logger logger = Logger.getLogger("CBLog"); 
fh = new FileHandler(CBDataPath + "\\CB.log"; 
logger.addHandler(fh); 
SimpleFormatter formatter = new SimpleFormatter(); 
fh.setFormatter(formatter); 
logger.info("CB started"); 

Ich mag würde zwei frühere Versionen der Protokolldatei für einen bestimmten Fall halten. Wie kann das am einfachsten gemacht werden?

Hier ist eine Idee, die ich habe. Ich könnte eine Ganzzahl pflegen, die die Laufnummer in der Case-Datenbank darstellt. Bei jedem weiteren Lauf wird die Protokolldatei CB_CaseA_n.log benannt, wobei n die Nummer des vorherigen Laufs plus 1 ist. Jedes Mal, wenn CB auf CaseA ausgeführt wird, wird im Verzeichnis CasaA nach allen CB_CaseA _ ?.-Protokolldateien gesucht und nur die 3 letzten Dateien werden beibehalten. D. h., In Lauf 10 von CB_CaseA_7 würde gelöscht werden. Scheint nicht sehr elegant.

Gibt es einen besseren Weg?

Antwort

1

Vom java.util.logging.FileHandler:

Zahl gibt an, wie viele Ausgabedateien, um durch (Standard: 1).

"% g" die Erzeugung Nummer gedreht Protokolle

einen Filehandler mit Zähl- und Erzeugungsmuster erstellen zu unterscheiden:

new FileHandler("CBDataPath + "\\CB%g.log, Integer.MAX_VALUE, 2, false); 
+0

Vielen Dank! Teuflisch, ich habe gerade meinen eigenen Hack beendet! Ich werde deinen Vorschlag versuchen. –

+0

Und entschuldigen Sie die Formatierung des Codes, oder besser, dessen Fehlen. Ich platzierte in 4 und dann eingefügt ... denke, es hat nicht funktioniert. –

+0

Hoppla. Scheint ein Problem zu sein. Zusätzlich zum Erstellen von CB0.log wird CB0.log.lck erstellt. Letzteres wird gelöscht, wenn das Programm abgeschlossen ist. Soweit ich das verstehe, bedeutet dies, dass die Protokolldatei bereits in einem anderen Prozess existiert hat. Ich habe nur Ihre neue FileHandler Zeile (mit leichten Korrekturen "anstelle von mir. –

0

Hier ist meine Lösung. Die Erklärung:

updateLogHistory() maintains historical log files in the MyConcourses directory. It is called in the ConcoursGUI() constructor. 

The intuition is a "stack" of log files with the current log, i.e., ConcoursBuilderLog_0.log, on top. To make room for a new log file 
for the ConcoursBuilder session, any existing log files have to be "pushed down." However, the stack is allowed to hold only a prescribed 
number, size, elements so if there are already size files in the stack the bottom one gets deleted, or rather, overwritten. When the function 
finishes the top TWO will be identical, so the top one can be overwritten in the caller. 

It's important to note that "stack" is a metaphor here; there isn't a stack in the sense of a programed data structure. There can be only 
size log files in the MyConcourses folder. What actually happens in a so-called push is the CONTENTS of ConcoursBuilderLog_i.log 

wird in ConcoursBuilderLog_i kopiert + 1.log, so dass ConcoursBuilderLog_i.log unverändert.

// The algorithm below requires an initial ConcoursBuilder_0.log. Consequently, prior to calling updateLogHistory() 
// the directory is first checked and an empty one is created if absent. Typically, this happens only in the first 
// run after INSTALLATION of ConcoursBuilder. However, it must be checked because the user might accidently deleted it. 
// 
// Work from the bottom up to push all existing log files down, leaving the contents of the current ConcoursBuilderLog_0 in 
// both ConcoursBuilderLog_0 and 1. the subsequent log file will overwrite both ConcoursBuilderLog_0. 
// 



Logger logger = Logger.getLogger("ConcoursBuilderLog"); 
File logFile = null; 
try { 
    String strFileFullPath = concoursBuilderDataPath + "\\ConcoursBuilderLog_" + 0 + ".log"; 
    logFile = new File(strFileFullPath); 
    if(!logFile.exists()){ 
     try { 
      logFile.createNewFile(); 
     } catch (IOException ex) { 
      Logger.getLogger(ConcoursGUI.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     try {    
      Files.write(Paths.get(logFile.getPath()), "Empty log file".getBytes(), StandardOpenOption.WRITE); 
     } catch (IOException ex) { 
      Logger.getLogger(ConcoursGUI.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
    // Maintain a "stack" of historical ConcoursBuilder log files. 
    updateLogHistory(NUM_SAVED_LOGS, logFile); 

} catch (SecurityException e) { 
    e.printStackTrace(); 
} 
fhLogger = null; 
try { 
    fhLogger = new FileHandler(logFile.toString(), false); 
} catch (IOException ex) { 
    Logger.getLogger(ConcoursGUI.class.getName()).log(Level.SEVERE, null, ex); 
} catch (SecurityException ex) { 
    Logger.getLogger(ConcoursGUI.class.getName()).log(Level.SEVERE, null, ex); 
} 
logger.addHandler(fhLogger); 
logger.setLevel(Level.ALL); 
SimpleFormatter formatter = new SimpleFormatter(); 
fhLogger.setFormatter(formatter); 

// the updater 
private static void updateLogHistory(int size, File logFile0){ 
     String strTemp = logFile0.toString(); 
    String strPrefix = strTemp.substring(0, strTemp.indexOf("_")+1); 
    for(int i = size-1; i >=0; i--){ 
     String strFileFullPath = strPrefix + i + ".log"; 
     File logFile_i = new File(strFileFullPath); 
     if(logFile_i.exists() && !logFile_i.isDirectory()){ 
      Path path= Paths.get(strFileFullPath); // this is the the absolute path to the i file as a Path     
      if(i != size-1){ 
       // not at the end so there is a valid file name i+1. 
       // Note that the file selected by iNext has already been pushed into iNext+1, or is the last. Either way, 
       // it can properly be overwritten. 
       int iPlus1 = i + 1; 
       String strFileFullPathIPlus1 = strPrefix + iPlus1 + ".log"; 
       Path pathIPlus1 = Paths.get(strFileFullPathIPlus1); // absolute path to the file as a Path     
       try { 
        Files.copy(path, pathIPlus1, REPLACE_EXISTING); 
       } catch (IOException ex) { 
        okDialog("IOException while updating log history in updateLogHistory()"); 
        Logger.getLogger(ConcoursGUI.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       continue; // (unnecessary) branch back to for() 
      } else{ 
       // Getting here means stack is full. IOW, the reference file the is last log file to be kept so we no longer need it's contents. 
       // No action required since it will simply be overwritten in the next pass. 
       // things in the next pass.; 
      } 
     } 
    } 

}  
Verwandte Themen