[Basic] Log output to the consol or a file from Basic

Shared Libraries
Forum rules
For sharing working examples of macros / scripts. These can be in any script language supported by OpenOffice.org [Basic, Python, Netbean] or as source code files in Java or C# even - but requires the actual source code listing. This section is not for asking questions about writing your own macros.
Post Reply
hanya
Volunteer
Posts: 885
Joined: Fri Nov 23, 2007 9:27 am
Location: Japan

[Basic] Log output to the consol or a file from Basic

Post by hanya »

There is not runtime function to output to the console from OOo Basic. But sometimes you want to confirm values without debugging or using msgbox function. Use css.logging.ConsolHandler to output log into your console. The console output does not work on Windows environment. There is another logger to output log record to a file: css.logging.FileHandler.

This macro output log record to the console or a file using these services. You can switch the output with nLogIntoFile_Logging constant, see below.

Code: Select all

'//-- Customizable Logging function --
' Make the log to the console or a file.
' Usage:
'  Logg(sLogMessage [, nLogLevel] [, sName1] [, sName2])
'
'   sLogMessage (string): message 
'   nLogLevel (long)    : log level. if you do not specify, nDefaultLogLevel_Logging is used.
'   sName1 (string)     : optional string. This is not used in default impl.
'   sName2 (string)     : also optional. If you want to add additional information for log, 
'                         please edit "CustomLogFormatter_format" function for output.
'
' Please customize CustomLogFormatter_format function for your purpose.
' The output to the console does not work on Windows environment.
' 
' Log message is going to ouput if nLogLevel is grater or equal to nThreshold_Logging value.

'//-- variables
' threshold to show log message
Const nThreshold_Logging = 900 'com.sun.star.logging.LogLevel.WARNING
Const nDefaultLogLevel_Logging = 800 'com.sun.star.logging.LogLevel.INFO
Const sDefaultEncoding_Logging = "utf-8"
Const sLoggerName_Logging = "OOo Basic"

' for file output
Const nLogIntoFile_Logging = 0 ' 0 for console output, 1 for file output
' specify a file URL to write, substituted by css.util.PathSubstitution during initialization
Const sFileURL_Logging = "$(user)/temp/basic.log"


'//-- formatting log output
' you can customize output string. This function of css.logging.XLogFormatter interface 
' is called from the log handler.
' Append line feed or carrige return at the end of the line.
Function CustomLogFormatter_format(aRecord As com.sun.star.logging.LogRecord) As String
  Dim sLog As String
  sLog = FormatDate_Logging(aRecord.LogTime) & _
      " " & aRecord.Message
  CustomLogFormatter_format = sLog & chr(10)
End Function


Dim oLogger_Logging As Object ' object for logging
Dim nSequenceNumber_Logging As Long ' for sequencial numbering

'//-- to log
'   sMessage: message string to show information about the situation
'   nLogLevel: one of a member of css.logging.LogLevel constants
'   sSourceClassName: Like a module name, optional
'   sSourceMethodName: sub or function name, optional
Sub Logg(Optional sMessage As String, Optional nLogLevel As Long, _
        Optional sSourceClassName As String, Optional sSourceMethodName As String)
  If IsNull(oLogger_Logging) Then
    ' create new logger
    nSequenceNumber_Logging = 0
    
    If nLogIntoFile_Logging = 0 Then
      ' for consol output
      oLogger_Logging = CreateUnoService("com.sun.star.logging.ConsoleHandler")
      
      oLogFormatter_Logging = CreateUnoListener("CustomLogFormatter_", _
         "com.sun.star.logging.XLogFormatter")
      
      Dim aArgs_Logging(2) As New com.sun.star.beans.NamedValue
      aArgs_Logging(0).Name = "Formatter"
      aArgs_Logging(0).Value = oLogFormatter_Logging
      aArgs_Logging(1).Name = "Encoding"
      aArgs_Logging(1).Value = sDefaultEncoding_Logging
      aArgs_Logging(2).Name = "Level"
      aArgs_Logging(2).Value = nThreshold_Logging
      
      oLogger_Logging.initialize(Array(aArgs_Logging))
      oLogger_Logging.Threshold = nThreshold_Logging
    Else
      ' for file output
      oLogger_Logging = CreateUnoService("com.sun.star.logging.FileHandler")
      
      oLogFormatter_Logging = CreateUnoListener("CustomLogFormatter_", _
         "com.sun.star.logging.XLogFormatter")
      
      Dim aArgs1_Logging(3) As New com.sun.star.beans.NamedValue
      aArgs1_Logging(0).Name = "Formatter"
      aArgs1_Logging(0).Value = oLogFormatter_Logging
      aArgs1_Logging(1).Name = "Encoding"
      aArgs1_Logging(1).Value = sDefaultEncoding_Logging
      aArgs1_Logging(2).Name = "Level"
      aArgs1_Logging(2).Value = nThreshold_Logging
      aArgs1_Logging(3).Name = "FileURL"
      aArgs1_Logging(3).Value = sFileURL_Logging
      
      oLogger_Logging.initialize(Array(aArgs1_Logging))
    End If
    
  End If
  If NOT IsNull(oLogger_Logging) Then
    If IsMissing(nLogLevel) Then nLogLevel = nDefaultLogLevel_Logging
    If IsMissing(sSourceClassName) Then sSourceClassName = ""
    If IsMissing(sSourceMethodName) Then sSourceMethodName = ""
    oLogger_Logging.publish( _
        LogEntry_Logging(sMessage, nLogLevel, _
            sSourceClassName, sSourceMethodName, nSequenceNumber_Logging))
    oLogger_Logging.flush() ' force output
    nSequenceNumber_Logging = nSequenceNumber_Logging + 1
  End If
End Sub


' create new log entry
' nLogLevel: specified one of entry from constant group of css.logging.LogLevel
Function LogEntry_Logging(sMessage As String, nLogLevel As Long, _
        sSourceClassName As String, sSourceMethodName As String, _
        nSequenceNumber As Long)
  aRecord = CreateUnoStruct("com.sun.star.logging.LogRecord")
  aDateTime = CreateUnoStruct("com.sun.star.util.DateTime")
  vNow = Now()
  With aDateTime
    .Year = Year(vNow)
    .Month = Month(vNow)
    .Day = Day(vNow)
    .Hours = Hour(vNow)
    .Minutes = Minute(vNow)
    .Seconds = Second(vNow)
  End With
  With aRecord
    .LoggerName = sLoggerName
    .SourceClassName = sSourceClassName
    .SourceMethodName = sSourceMethodName
    .Message = sMessage
    .LogTime = aDateTime
    .SequenceNumber = nSequenceNumber
    .ThreadID = 0
    .Level = nLogLevel
  End With
  
  LogEntry_Logging = aRecord
End Function


' they are not called from the console handler
Function CustomLogFormatter_getHead()
  CustomLogFormatter_getHead = ""
End Function
Function CustomLogFormatter_getTail()
  CustomLogFormatter_getTail = ""
End Function


' to make date and time format
Function FormatDate_Logging(aDateTime As com.sun.star.util.DateTime) As String
  FormatDate_Logging = "[" & Format(aDateTime.Year, "0000-") & _
      Format(aDateTime.Month, "00-") & Format(aDateTime.Day, "00 ") & _
      Format(aDateTime.Hours, "00:") & Format(aDateTime.Minutes, "00:") & _
      Format(aDateTime.Seconds, "00") & "]"
End Function
'//--
Put the macro into your module of the basic. Customize constants and formatter, and then write like the following to output log record:

Code: Select all

Sub main_log_test
  ' do something....
  Logg("This is log message.", 900) ' log level is the same as the threshold, 
  Logg("This message is not shown.") ' default log level is used
  Logg("Please modify nDefaultLogLevel_Logging constant to change the default log level.", 800)
End Sub
If you want to see the log output on your console, please start your office through the console.
Please, edit this thread's initial post and add "[Solved]" to the subject line if your problem has been solved.
Apache OpenOffice 4-dev on Xubuntu 14.04
B Marcelly
Volunteer
Posts: 1160
Joined: Mon Oct 08, 2007 1:26 am
Location: France, Paris area

Re: [Basic] Log output to the consol or a file from Basic

Post by B Marcelly »

Hi,
Well, rather complex code...

Here is a simple log to file, in pure Basic, tested on MS-Windows.
Put this macro in a module of library Standard of My Macros.

Code: Select all

REM  *****  BASIC  *****

Option Explicit

Private Const logFileAddress = "C:\Docs OpenOffice\OOoLog.txt"

Sub Logg(Optional sMessage As String)
Dim f1 As Integer

if IsMissing(sMessage)  then ' delete all log data
  if FileExists(logFileAddress)  then Kill logFileAddress
  Exit Sub
end if

f1 = FreeFile
Open logFileAddress For Append As #f1
print #f1, Now & " : " & sMessage
Close #f1
End Sub
Here is an example of use. Logg without argument clears the log file.

Code: Select all

Sub Main
Logg
Logg("Hello")
Logg("This is a message")
Logg("Finished !")
End Sub
A simple text editor will display the file text.
If your tested code crashes, you will still have the log lines before the crash.
Of course this is a sketch, you may create a more sophisticated Logg macro.
Bernard

OpenOffice.org 1.1.5 / Apache OpenOffice 4.1.1 / LibreOffice 5.0.5
MS-Windows 7 Home SP1
Post Reply