Class: Logical::Naf::LogFile

Inherits:
Object
  • Object
show all
Defined in:
app/models/logical/naf/log_file.rb

Constant Summary collapse

LOG_MAX_SIZE =
50_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(log_area) ⇒ LogFile

Returns a new instance of LogFile.



12
13
14
15
16
17
# File 'app/models/logical/naf/log_file.rb', line 12

def initialize(log_area)
  @file_line_number = @line_number = 1
  @file = nil
  @log_area = log_area
  @lines_cache = ''
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



6
7
8
# File 'app/models/logical/naf/log_file.rb', line 6

def file
  @file
end

#file_line_numberObject (readonly)

Returns the value of attribute file_line_number.



6
7
8
# File 'app/models/logical/naf/log_file.rb', line 6

def file_line_number
  @file_line_number
end

#line_numberObject (readonly)

Returns the value of attribute line_number.



6
7
8
# File 'app/models/logical/naf/log_file.rb', line 6

def line_number
  @line_number
end

#lines_cacheObject (readonly)

Returns the value of attribute lines_cache.



6
7
8
# File 'app/models/logical/naf/log_file.rb', line 6

def lines_cache
  @lines_cache
end

#log_areaObject (readonly)

Returns the value of attribute log_area.



6
7
8
# File 'app/models/logical/naf/log_file.rb', line 6

def log_area
  @log_area
end

Instance Method Details

#<<(message) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'app/models/logical/naf/log_file.rb', line 19

def <<(message)
  log_line = JSON.pretty_generate({
    line_number: line_number,
    output_time: Time.zone.now.strftime("%Y-%m-%d %H:%M:%S.%L"),
    message: message
   })
  @lines_cache << log_line
  @line_number += 1
end

#check_file_sizeObject



60
61
62
63
64
65
66
# File 'app/models/logical/naf/log_file.rb', line 60

def check_file_size
  if file.size > LOG_MAX_SIZE
    @file_line_number = line_number
    close
    @file = File.open(log_area + "/#{file_line_number}_#{Time.zone.now.strftime('%Y%m%d_%H%M%S')}.json", 'wb')
  end
end

#closeObject



55
56
57
58
# File 'app/models/logical/naf/log_file.rb', line 55

def close
  @file.try(:close)
  @file = nil
end

#flushObject



39
40
41
# File 'app/models/logical/naf/log_file.rb', line 39

def flush
  file.flush
end

#openObject



43
44
45
46
47
48
49
50
51
52
53
# File 'app/models/logical/naf/log_file.rb', line 43

def open
  # Create the directory path if it doesn't exist
  FileUtils.mkdir_p(log_area)

  filename = Dir[log_area + "/#{file_line_number}_*"].first
  if filename.blank?
    @file = File.open(log_area + "/#{file_line_number}_#{Time.zone.now.strftime('%Y%m%d_%H%M%S')}.json", 'wb')
  else
    @file = File.open(filename, 'wb')
  end
end

#writeObject



29
30
31
32
33
34
35
36
37
# File 'app/models/logical/naf/log_file.rb', line 29

def write
  check_file_size
  output = lines_cache
  unless output.blank?
    file.write(output)
    @lines_cache = ''
    flush
  end
end