Wixsharp: Log file location

Created on 19 Jun 2018  ·  17Comments  ·  Source: oleg-shilo/wixsharp

Could you please help me set a custom location for bootstrapper log file?

Thank you

TipHints question

All 17 comments

From command line: setup.exe -l "<log file path>"

Otherwise yob can add the <Log PathVariable="<log file path>"/> to the Bundle element, but then... it becomes hard-codded.

Thank you!

@oleg-shilo How can I add the <Log PathVariable="<log file path>"/> to the Bundle element? I'm working on MBA where i have embedded WPF assembly. I want it to be able to open log file from the WPF app, hence I need somehow to write the log file always to a defined location to be able to open in from the WPF app. Thank you.

You can parse BootstrapperApplicationData.xml to get a LogPathVariable

<WixBundleProperties DisplayName="NVR" LogPathVariable="WixBundleLog" Compressed="no" Id="{bc79cd51-0a66-4856-85ae}" UpgradeCode="{17114591-A412-4534-B0A1}" PerMachine="yes" />

```xml
[0E40:1610][2019-02-25T14:53:28]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\ms\AppData\Local\Temp\NVR_20190225145328.log'

With `LogPathVariable`, you can get the full path to the log file.
```C#
 var log = Engine.StringVariables[WixBundleLog];

Thanks for your prompt reply. I'm a bit confused. Where does this parsing has to happen?
I thought I could put it somewhere during the Bundle creation. Like:

            var bootstrapper =
              new Bundle(APP_NAME, new MsiPackage(blabla), new LogEntry(...)

Is there a way to change the wix bundle properties via LightOptions?

This should be in your MBA.

Not sure if you understood my concern correctly. I need my Bootstrapper to log to a file by default w/o providing -l argument.
You suggested to parse BootstrapperApplicationData.xml file, which I am not sure where and when this file is created. Nor I don't see how I can set up the log path by parsing it.

В сборке, в которой ты реализуешь WPF, должен быть парсер BootstrapperApplicationData.xml, этот файл будет создан при запуске инсталлятора, к нему можно добраться так:
```C#
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "BootstrapperApplicationData.xml");

 в этой xml содержится много информации о твоем бутстраппере. в частности в тэге `LogPathVariable` записана название переменной в которой будет храниться путь к лог файлу, стандартное имя это `WixBundleLog`.
Имея имя переменной ты можешь у бутстраппера запросить содержимое переменной:
```C#
 var log = Engine.StringVariables[WixBundleLog];

И я не вижу смысла настраивать путь к лог файлу. пусть остается тот что по умолчанию, ты всегда можешь получить к нему путь.

Спасибо за помощь. Все равно что-то я не очень понимаю:)
не вижу ничего похожено на BootstrapperApplicationData.xml.
Я делаю по примеру: Samples->Bootstrapper->WixBootstrapper_UI.
У меня изначальная проблема такая, я хочу добавить кнопку "Show Log" на MainView, чтоб по нажатию открывался log инсталлера. Я не могу получить доступ к MsiSession из WPF проекта. Все что я имею там, это BootstrapperApplication. Поэтому я подумал, почему-бы не сделать так, чтоб лог все время писался в одно и то же место, а при нажатии на Show Log, программа бы просто открывала файл. Но я не могу установить WixBundleLog переменную, не знаю как.

Собери свой проект и запусти бутстраппер, в папке Temp появится 2 папки в название которых будут гуиды. в одной из этих папок будет еще папка с названием .ba, вот в ней и будет лежать BootstrapperApplicationData.xml. т.е. эта хмл появляется только когда твой бутстраппер запущен.

если ты делаешь по примеру Samples->Bootstrapper->WixBootstrapper_UI
то можешь впихнуть обработку xml в конструктор MainViewModel

Ага, файл нашел. Так лог файл всегда создается? Я думал он создается только тогда, когда bootstrapper запущен с парамертом -l filename.log. Этот параметр просто переназначает путь логфайла? О чем тогда Олег писал вверху:

Otherwise yob can add the `<Log PathVariable="<log file path>"/>` to the `Bundle` element, but then... it becomes hard-codded.

Лог файл создается всегда, к сожалению я не знаком с этим параметром, но думаю что этот параметр может переопределить имя и/или путь лог файла, ничего конкретного сказать не могу

Будут вопросы пиши.

I meant Log element of the Bundle: http://wixtoolset.org/documentation/manual/v3/xsd/wix/log.html

Since WixSharp does not expose this element directly you may need to inject it. Something like that:
```C#
bootstrapper.AddWixFragment("Wix/Bundle", XElement.Parse(@""));

bootstrapper.Variables = new[]
{
new Variable("LogFileLocation", "[TempFolder]\YourProduct\") { Overridable = true }
};

or as this:

```C#
bootstrapper.WixSourceGenerated += 
    doc => doc.Root
              .Select("Bundle")
              .AddElement("Log", "PathVariable=LogFileLocation");

bootstrapper.Variables = new[] 
{ 
    new Variable("LogFileLocation", "[TempFolder]\YourProduct\") { Overridable = true }
};

And when you show the file you can access it as
```C#
var log = Bootstrapper.Engine.StringVariables["LogFileLocation"];

And if you ever want to overwrite this location from `MainViewModel` do it as this: 
```C#    
Bootstrapper.Engine.StringVariables["LogFileLocation"] = <whatever you want>;

That's great, thank you. This is what I was looking for.

Was this page helpful?
0 / 5 - 0 ratings