' Software- und Organisations-Service GmbH, 2005, www.sos-berlin.com
' Andreas Püschel, 2006-05-20, andreas.pueschel@sos-berlin.com
'
' This script demonstrates the usage of the API methods of Microsoft LogParser
' and of the Job Scheduler for analysis or conversion of log files:


Option Explicit

Function spooler_process()

  Dim oLogQuery, oInputFormat, oOutputFormat, strQuery, inputFormat, inputSpec, outputFormat, outputSpec, outputConnection

  spooler_process = false

  ' job parameter defaults
  inputFormat      = "TEXTLINEInputFormat"
  inputSpec        = spooler_log.filename
  outputFormat     = "TSVOutputFormat"
  outputSpec       = "logs/" & spooler_job.name & ".csv"
  outputConnection = ""


  If spooler_task.params.value("input_format") <> "" Then
    inputFormat = spooler_task.params.value("input_format")
  End If

  If spooler_task.params.value("input_files") <> "" Then
    inputSpec = spooler_task.params.value("input_spec")
  End If

  If spooler_task.params.value("output_format") <> "" Then
    outputFormat = spooler_task.params.value("output_format")
  End If

  If spooler_task.params.value("output_spec") <> "" Then
    outputSpec = spooler_task.params.value("output_spec")
  End If

  If spooler_task.params.value("output_connection") <> "" Then
    outputConnection = spooler_task.params.value("output_connection")
  End If


  ' parameter checking
  If LCase(outputSpec) = "sqloutputformat" And outputConnection = "" Then
     spooler_log.warn "no connect string was given for output database connection"
     Exit Function
  End If


  Set oLogQuery = CreateObject("MSUtil.LogQuery")

  ' Create Input Format object
  Set oInputFormat = CreateObject("MSUtil.LogQuery." & inputFormat)

  ' Create Output Format object
  Set oOutputFormat = CreateObject("MSUtil.LogQuery." & outputFormat)

  Select Case LCase(outputFormat)
    case "tsvoutputformat":
              oOutputFormat.oSeparator = "tab"
              oOutputFormat.oTsFormat = "yyyy-MM-dd hh:mm:ss"
    case "sqloutputformat":
              oOutputFormat.createTable = true
              oOutputFormat.transactionRowCount = -1
              oOutputFormat.ignoreMinWarns = true
              oOutputFormat.ignoreIdCols = true
              oOutputFormat.oConnString = outputConnection
  End Select

  ' Create query text
  strQuery = "SELECT EXTRACT_PREFIX(Text, 1, ' ') as created, EXTRACT_TOKEN(Text, 2, ' ') as message_type, EXTRACT_SUFFIX(Text, 3, ' ') as message_content"
  strQuery = strQuery & " INTO " & outputSpec & " FROM " & inputSpec
  strQuery = strQuery & " WHERE EXTRACT_TOKEN(Text, 2, ' ') IN ('[WARN]'; '[ERROR]'; '[info]')"

  ' Execute query
  oLogQuery.ExecuteBatch strQuery, oInputFormat, oOutputFormat

  spooler_log.info oLogQuery.outputUnitsProcessed & " output records written"

End Function